自定义UITableViewCell UIButton

问题描述:

我有一个自定义UITableViewCell有几个按钮。当代码被全部下一个视图控制器,我的按钮被声明如下:自定义UITableViewCell UIButton

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 

我知道这是常见设置标签物业indexPath.row在表视图使用的UIButton。但是,我在数据源中使用两个单独的数组来填充TableView的两个不同部分,所以我认为这不会起作用。

+0

也许它只是我,但按钮的代码看起来完全一样。 – 2011-03-01 13:03:15

+0

也许你的代码并不是真的那样,但你并没有添加你创建的同一个按钮(myButton vs damageButton)。 – jv42 2011-03-01 13:24:31

+0

@fluchtpunkt - 唯一的区别是目标是一个视图控制器,我作为一个属性传递 – DVG 2011-03-01 14:23:32

的问题,在端部,是,我是添加子视图的单元对象,而不是内容查看的细胞对象。我改变了这个按钮代码,它被解决了:

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

不要继承UITableViewCell(或UITableView),它通常是不必要的,可能会导致问题。表单元格有一个contentView这是一个定制的好地方。

推荐阅读:

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

然后:

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

+0

嗯。我是UITableViewCell的子类来处理我遇到的滚动性能问题。也许有更好的办法。 – DVG 2011-03-01 14:26:56

+2

我总是继承UITableViewCell以避免在ViewControllers中放置大量表示代码,而是将其放置在独立的单元类中。 – jv42 2011-03-01 15:20:52

+0

但我同意你所链接的文章:不要滥用子类,特别是不要将它用于错误的原因。 – jv42 2011-03-01 15:23:35