[英]Custom UITableViewCell with button
我将UITableViewCell子类化,并为其添加了一个按钮。 触摸按钮后如何响应事件? 我还需要知道按下按钮的索引路径。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CustomTableCell";
CustomTableCell *cell = (CustomTableCell *)
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle]
loadNibNamed:@"CustomTableCell"
owner:nil options:nil];
for (id currentObjects in topLevelObjects){
if ([currentObjects isKindOfClass:[StatusTableCell class]]){
cell = (StatusTableCell *) currentObjects;
break;
}
}
}
cell.customButton.tag = indexPath.row;
return cell;
}
如果您已通过代码在UITableViewCell子类中添加了UIButton,则可以使用以下代码为其添加操作。
//In UITableViewCell subclass
[customButton addTarget:self
action:@selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
然后,您已经编写了用于通过设置访问行号的代码,
cell.customButton.tag = indexPath.row;
您可以在aMethod中获取标签值,然后访问indexPath.row值,如下所示,
//In UITableViewCell subclass
-(IBAction)aMethod:(UIButton*)button
{
NSLog(@"indexPath.row value : %d", button.tag);
}
您可以在CustomTableCell Nib中分配IBAction,然后在函数中执行以下操作:
- (IBAction) btnDoSomethingPressed:(id)sender {
NSIndexPath *indexPath = [yourTableView indexPathForCell:(UITableViewCell *)[[sender superview] superview]];
//Use indexPath (or indexPath.row) like you would in a UITableViewDelegate method
}
假设yourTableView
是分配给表的实例变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.