[英]Custom UITableViewCell with button
I subclassed UITableViewCell and added a button to it. 我将UITableViewCell子类化,并为其添加了一个按钮。 How do I response to the event when the button is touched?
触摸按钮后如何响应事件? I also need to know which index path was the button pressed on.
我还需要知道按下按钮的索引路径。
- (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;
}
If you have added the UIButton by code in your UITableViewCell Subclass you can use the following code to add an action for it. 如果您已通过代码在UITableViewCell子类中添加了UIButton,则可以使用以下代码为其添加操作。
//In UITableViewCell subclass
[customButton addTarget:self
action:@selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
And then you have already written the code for accessing the row number by setting, 然后,您已经编写了用于通过设置访问行号的代码,
cell.customButton.tag = indexPath.row;
You can get the tag value in the aMethod and access the indexPath.row value like below, 您可以在aMethod中获取标签值,然后访问indexPath.row值,如下所示,
//In UITableViewCell subclass
-(IBAction)aMethod:(UIButton*)button
{
NSLog(@"indexPath.row value : %d", button.tag);
}
You can assign the IBAction in the CustomTableCell Nib and in the function do something like this: 您可以在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
}
This assumes that yourTableView
is an instance variable assigned to your table. 假设
yourTableView
是分配给表的实例变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.