3

カスタムセル内にUIButtonがあり、ユーザーがそのボタンを押したときにアクションをトリガーしたいのですが、UIButtonが押された行を知る必要があります。

これが私のコードです:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;

    ...

    [button addTarget:self action:@selector(buttonPressedAction:)forControlEvents:UIControlEventTouchUpInside];

}

- (void)buttonPressedAction:(UIButton *)button
{
    //int row = indexPath.row;
    //NSLog(@"ROW: %i",row);
}

indexPath を引数としてセレクターに渡すにはどうすればよいですか?

4

4 に答える 4

6

ボタンのタグ プロパティを行番号に設定することもできます。

button.tag = indexPath.row;

を使用して取得します

NSInteger row = button.tag;

または、インデックス パス オブジェクト自体を関連付けられたオブジェクトとしてボタンに設定します。

objc_setAssociatedObject(button, "IndexPath", indexPath);

NSIndexPath *ip = objc_getAssociatedObject(button, "IndexPath");
于 2012-09-06T10:03:07.693 に答える
2

カスタム セルにボタンを追加するときにtag、UIButton のプロパティを次のように追加できます。

UIButton *sampleButton = [[UIButton alloc] init];
sampleButton.tag = indexPath.row;

そして、あなたが電話するとき、あなたはタグをチェックすることができます

- (void)buttonPressedAction:(UIButton*)sender
{
    if(sender.tag==0)
    {
      //perform action
    }
}

それが役に立てば幸い。幸せなコーディング:)

于 2012-09-06T10:04:29.423 に答える
1

シンプルなボタンタグを設定..

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;

    ...

    [button setTag = indexPath.row]; // Set button tag

    [button addTarget:self action:@selector(buttonPressedAction:)
                                            forControlEvents:UIControlEventTouchUpInside];
    }

    - (void)buttonPressedAction:(id)sender
    {
        UIButton *button = (UIButton *)sender;
        int row = [button superview].tag;
    }
}
于 2012-09-06T10:06:32.857 に答える
1

タグを設定するよりも簡単です。これを試して..

indexPath を取得するには、次のコードを試してください。

UIView *contentView = (UIVIew *)[button superview];
UITableViewCell *cell = (UITableViewCell *)[contentView superview];
NSIndexPath *indexPath = [self.tableview indexPathForCell:cell];

また

NSIndexPath *indexPath = [self.tableview indexPathForCell:(UITableViewCell *)[(UIVIew *)[button superview] superview]];
于 2012-09-07T18:32:55.863 に答える