【问题标题】:how to add the plus button to the right side of the table view in objective-c?如何在objective-c的表格视图右侧添加加号按钮?
【发布时间】:2011-01-17 08:46:14
【问题描述】:

我想在表格视图的右侧添加加号按钮,以在其他视图中添加该单元格的内容。

如何在表格视图右侧添加加号按钮。

【问题讨论】:

    标签: iphone objective-c


    【解决方案1】:

    如果你有一个导航栏,你应该像这样添加一个 UIBarButtonItem:

    UIBarButtonItem *addButton = [[UIBarButtonItem alloc]      
        initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
        target:self action:@selector(addButtonPressed:)];
    self.navigationItem.rightBarButtonItem = addButton;
    

    【讨论】:

      【解决方案2】:
      1. 转到 iPhone Interface Guidelines Page

      2. 在“用于表格行和其他用户界面元素的标准按钮”下复制 ContactAdd 按钮(我在此处将其保存为 ContactAdd.png)。将其添加到您的项目中。

      3. 在cellForRowAtIndexPath:(NSIndexPath *)indexPath方法中添加:

        UIImage *image = [UIImage imageNamed:@"ContactAdd.png"];
        
        
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        //You can also Use:
        //UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
        
        CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
        
        //match the button's size with the image size
        button.frame = frame;
        
        [button setBackgroundImage:image forState:UIControlStateNormal];
        
        // set the button's target to this table view controller so you can open the next view
        [button addTarget:self action:@selector(yourFunctionToNextView:) forControlEvents:UIControlEventTouchUpInside];
        
        button.backgroundColor = [UIColor clearColor];
        
        cell.accessoryView = button;
        

      【讨论】:

      • *注意:除了复制和添加之外,您还可以使用:[UIButton buttonWithType:UIButtonTypeContactAdd];而不是 UIButtonTypeCustom.
      • 执行上述任一操作的棘手部分是将参数传递给 yourFunctionToNextView: 以便了解按下了哪一行。这可以通过 button.tag=row 轻松完成;但是,如果您的表中有部分,则单个 int 是不够的。您需要传递 indexPath。我在这里找到了这种方法来做这样的事情。 stackoverflow.com/questions/5500327/…
      • 是的,传递参数是棘手的部分。您的链接几乎是完整的,只是它没有告诉您如何传递您添加到 UIButton 类的属性。只是为了完成这个想法,只有在选择器中的“yourFunctionToNextView:”之后包含“:”时才会传递参数。因此,上面的示例将使用 button.property=indexPath 进行扩展。然后,选择器的定义将是:-(void)yourFunctionToNextView:(UIButton*)sender {}。然后在这个方法中,你可以使用类似 NSIndexPath *indexPath = sender.property;其中属性是 indexPath。
      • 投反对票,因为它是一个可怕的黑客。请参阅下面有关如何正确执行此操作的答案。
      【解决方案3】:

      对于斯威夫特

      let addButton = UIBarButtonItem.init(barButtonSystemItem: .Add,
                                           target: self,
                                           action: #selector(yourFunction))
      self.navigationItem.rightBarButtonItem = addButton
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多