DVG*_*DVG 1 iphone uitableview
我有一个自定义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];
Run Code Online (Sandbox Code Playgroud)
昨晚我将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];
Run Code Online (Sandbox Code Playgroud)
但是,由于这样做,按下任何单元格上的按钮会导致操作仅影响表格中的第一行,我不知道为什么.
行动代码:
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
Run Code Online (Sandbox Code Playgroud)
我理解将Tag属性设置为indexPath.row以在表视图中使用UIButton是很常见的.但是,我在数据源中使用两个单独的数组来填充TableView的两个不同部分,所以我认为这不会起作用.
最后,问题是我将子视图添加到单元格对象而不是单元格对象的内容视图.我将按钮代码更改为此并解决了:
UIButton *button = (UIButton *)sender;
UITableViewCell *cell = (UITableViewCell *)[button superview];
NSIndexPath *indexPath = [[self tableView] indexPathForCell:cell];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2592 次 |
| 最近记录: |