[英]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.