【问题标题】:UIButton on Custom UITableViewCell自定义 UITableViewCell 上的 UIButton
【发布时间】:2011-03-03 20:59:02
【问题描述】:

我有一个自定义 UITableViewCell 有几个按钮。当代码都在一个视图控制器下时,我的按钮声明如下:

myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton addTarget:self
             action:@selector(myButtonAction:)
   forControlEvents:UIControlEventTouchUpInside];
[myButton setTitle:@"Action" forState:UIControlStateNormal];
myButton.frame = CGRectMake(20, 80, 72, 37);
[self addSubview:myButton];

昨晚我继承了UITableViewCell,所以代码变成了这样:

myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton addTarget:viewController
             action:@selector(myButtonAction:)
   forControlEvents:UIControlEventTouchUpInside];
[myButton setTitle:@"Action" forState:UIControlStateNormal];
myButton.frame = CGRectMake(20, 80, 72, 37);
[self addSubview:damageButton];

然而,由于这样做,按下任何单元格上的按钮会导致该操作仅影响表格中的第一行,我不确定为什么。

动作代码:

UIButton *button = (UIButton *)sender;
UIView *contentView = [button superview];
UITableViewCell *cell = (UITableViewCell *)[contentView superview];
NSIndexPath *indexPath = [[self tableView] indexPathForCell:cell];

//do something with objectAtIndex:indexPath.row

我了解将 Tag 属性设置为 indexPath.row 以在表格视图中使用 UIButton 是很常见的。但是,我在数据源中使用了两个单独的数组来填充 TableView 的两个不同部分,所以我认为这不会起作用。

【问题讨论】:

  • 也许只有我一个人,但按钮的代码看起来完全一样。
  • 也许你的代码不是真的那样,但你没有添加你正在创建的相同按钮(myButton vs damageButton)。
  • @fluchtpunkt - 唯一的区别是目标是我作为属性传递的视图控制器
  • @jv42 正在重命名东西以使其通用,错过了那个。

标签: iphone uitableview


【解决方案1】:

最后,问题是我将子视图添加到单元格对象,而不是单元格对象的内容视图。我将按钮代码更改为此并已解决:

UIButton *button = (UIButton *)sender;
UITableViewCell *cell = (UITableViewCell *)[button superview];
NSIndexPath *indexPath = [[self tableView] indexPathForCell:cell];

【讨论】:

    【解决方案2】:

    不要子类化 UITableViewCell(或 UITableView),这通常是不必要的,并且会导致问题。表格单元格有一个contentView,这是一个自定义的好地方。

    推荐阅读:

    http://cocoawithlove.com/2009/04/easy-custom-uitableview-drawing.html

    然后:

    http://cocoawithlove.com/2010/12/uitableview-construction-drawing-and.html

    【讨论】:

    • 嗯。我正在继承 UITableViewCell 来处理我遇到的滚动性能问题。也许有更好的方法。
    • 我一直在继承 UITableViewCell 以避免在 ViewControllers 中放置大量演示代码,而是将其放在独立的单元格类中。
    • 但我同意你链接的文章:不要滥用子类化,特别是不要出于错误的原因使用它。
    • 实际绘图有时最好在 UITableViewCell 的 contentView 中完成(您可以为其提供渲染对象),而不是 UITableViewCell 本身。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多