我正在使用tableView加载一个自定义的UITableViewCell,里面有一个"Tap"按钮.用户单击按钮时会调用方法.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{...
[btnRowTap addTarget:self action:@selector(didButtonTouchUpInside:) forControlEvents:UIControlEventTouchDown];
...
return cell;
}
Run Code Online (Sandbox Code Playgroud)
在didButtonTouchUpInside方法中,我试图以下列方式检索所选行的值:
-(IBAction)didButtonTouchUpInside:(id)sender{
UIButton *btn = (UIButton *) sender;
UITableViewCell *cell = (UITableViewCell *)btn.superview;
NSIndexPath *indexPath = [matchingCustTable indexPathForCell:cell];
NSLog(@"%d",indexPath.row);
}
Run Code Online (Sandbox Code Playgroud)
问题是,在任何一行点击按钮时,我每次都得到相同的值0.我哪里错了?
您不能依赖UITableViewCell的视图层次结构.这种方法在iOS7中会失败,因为iOS7会更改单元格的视图层次结构.您的按钮和UITableViewCell之间会有一个额外的视图.
有更好的方法来处理这个问题.
.
-(IBAction)didButtonTouchUpInside:(id)sender{
UIButton *btn = (UIButton *) sender;
CGRect buttonFrameInTableView = [btn convertRect:btn.bounds toView:matchingCustTable];
NSIndexPath *indexPath = [matchingCustTable indexPathForRowAtPoint:buttonFrameInTableView.origin];
NSLog(@"%d",indexPath.row);
}
Run Code Online (Sandbox Code Playgroud)
将Button标签cellForRowAtIndexPath设置为方法Befor设置方法如
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{...
btnRowTap.tag=indexPath.row
[btnRowTap addTarget:self action:@selector(didButtonTouchUpInside:) forControlEvents:UIControlEventTouchDown];
...
return cell;
}
Run Code Online (Sandbox Code Playgroud)
你的tapped单元格如下: -
-(IBAction)didButtonTouchUpInside:(id)sender{
{
UIButton *button = (UIButton*)sender;
NSIndexPath *indPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
//Type cast it to CustomCell
UITableViewCell *cell = (UITableViewCell*)[tblView1 cellForRowAtIndexPath:indPath];
NSLog(@"%d",indPath.row);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4200 次 |
| 最近记录: |