【发布时间】:2026-02-05 12:40:02
【问题描述】:
我正在尝试在这篇文章中实施一个建议:Pass an argument to selector 使用objc_setAssociatedObject 和objc_getAssociatedObject 在UITableViewCell 中将@selector 参数传递给UIButton。我对其进行编码的方式,它总是最终通过它创建/加载的最后一个单元格的行。这是我的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *mainLabel;
soundButton=[UIButton buttonWithType:UIButtonTypeCustom];
if (cell == nil){
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
soundButton.tag = 33;
[soundButton addTarget:self action:@selector(soundButtonAction) forControlEvents:UIControlEventTouchUpInside];
[soundButton setFrame:CGRectMake(210,3,68, 37)];
[soundButton setBackgroundImage:[UIImage imageNamed:@"musicNote"] forState:UIControlStateNormal];
[cell.contentView addSubview:soundButton];
} else {
soundButton = (UIButton *)[cell.contentView viewWithTag:33];
}
objc_setAssociatedObject(soundButton, "IndexPath", indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
return cell;
}
-(void)soundButtonAction
{
NSIndexPath *ip = objc_getAssociatedObject(soundButton, "IndexPath");
【问题讨论】:
标签: iphone objective-c uitableview uibutton