【问题标题】:how to add a button without using custom cell on a UITableView?如何在不使用 UITableView 上的自定义单元格的情况下添加按钮?
【发布时间】:2009-05-12 06:59:32
【问题描述】:

如何在UITableViewCell 上添加自定义按钮,然后在不使用界面生成器和自定义单元格的情况下删除带有该按钮的单元格?

【问题讨论】:

    标签: iphone cocoa-touch uitableview


    【解决方案1】:

    如果你真的想在没有子类的情况下添加自定义按钮,只需将按钮添加到单元格的 contentView 中:

    [cell.contentView addSubview:customButton];
    

    您可以设置按钮的所有特性:框架、目标、选择器等...广告然后使用上述调用将其添加到单元格中。

    UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
    customButton.frame=//whatever
    [customButton setImage:anImage forState:UIControlStateNormal];
    [customButton setImage:anotherImage forState:UIControlStateHighlighted];
    [customButton addTarget:self action:@selector(delete) forControlEvents: UIControlEventTouchUpInside];
    //yadda, yadda, .....
    

    你也可以标记它

    customButton.tag = 99999;
    

    这样你以后可以找到它:

    UIButton *abutton = (UIButton*) [cell.contentView viewWithTag:99999];
    

    您需要决定何时添加按钮,可能是在单元格选择中,可能是在编辑模式中...只需将代码放入您选择的委托方法中即可。

    【讨论】:

      【解决方案2】:

      如果按钮的唯一目的是提供删除,您应该查看UITableViewDataSource,它有一个名为- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 的方法。像这样实现它:

          - (BOOL)tableView:(UITableView *)tableView 
      canEditRowAtIndexPath:(NSIndexPath *)indexPath 
      { 
         return YES; 
      }
      

      然后执行:

       - (void)tableView:(UITableView *)tableView 
      commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
       forRowAtIndexPath:(NSIndexPath *)indexPath 
      {
         // Database removal code goes here...
      }
      

      要使用这些方法,请让您的 UITableViewController 通过执行以下操作来实现 UITableViewDataSource 协议:

      MyClass : UITableViewController <UITableViewDataSource>
      

      在你的头文件中,一定要记得将viewController的数据源设置为self

      【讨论】:

      • 当我点击自定义按钮时我想做所有这些事情的按钮怎么样,并且必须在不使用界面构建器和自定义单元格的情况下创建按钮。
      • canEditRowAtIndexPath 方法在编辑模式下会自动在每一行添加一个删除按钮。试试看:)
      • 但我想用自定义按钮来做。
      • 告诉我如何在不使用界面生成器和自定义单元格的情况下添加自定义按钮。那么如何直接删除行以及数据库中的数据?
      • 我不确定自定义单元格是什么意思。但我想您可以在返回每行的单元格的方法中为每一行创建一个按钮,然后执行 [cell addSubview:yourButtonInstance]。请务必正确设置该按钮的目标和操作。 Action 可能类似于 -(void)deleteRow:(id)sender,其中 sender 是指向用户单击删除按钮的单元格的指针。但我不明白你为什么要那样做,但这当然不关我的事。
      猜你喜欢
      • 2011-02-14
      • 1970-01-01
      • 2014-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-10
      相关资源
      最近更新 更多