使用objc_setAssociatedObject为UITableViewCell传递UIButton @selector参数

时间:2013-02-17 07:54:08

标签: iphone objective-c uitableview uibutton

我正在尝试在此帖子中实施建议:Pass an argument to selector使用@selectorUIButton参数传递给UITableViewCell中的objc_setAssociatedObject objc_getAssociatedObject。我对它进行编码的方式总是最终传递它创建/加载的最后一个单元格的行。这是我的代码:

- (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");

1 个答案:

答案 0 :(得分:1)

看起来soundButton是你班上的伊娃?每次请求一个单元格时都会被覆盖,所以你只得到最后一个单元格。

我认为使用"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);