【发布时间】: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