[英]using objc_setAssociatedObject to pass UIButton @selector argument for UITableViewCell
我正在嘗試在本文中實現一個建議:使用objc_setAssociatedObject
和objc_getAssociatedObject
將參數傳遞給選擇器,以將@selector
參數傳遞給UITableViewCell
的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");
看起來soundButton
是您班上的一個ivar? 每次請求一個單元格時,它都會被覆蓋,因此您只會獲得最后一個單元格。
我也認為使用"IndexPath"
作為鍵不是一個好主意。
static char indexPathKey; // use address of indexPathKey as key
- (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:) /*extra :*/ 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, &indexPathKey, indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
return cell;
}
-(void)soundButtonAction:(UIButton *)sender
{
NSIndexPath *ip = objc_getAssociatedObject(sender, &indexPathKey);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.