在按钮上单击tableViewController [英] tableViewController on button click

查看:49
本文介绍了在按钮上单击tableViewController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个tableViewController,单元格包含一个按钮和一个标签.当用户单击按钮时,我需要获取单元格的文本(实际上是单元格Person的对象).

I have a tableViewController, the cells contains a button and a label. I need to get the text of the cell (actually the object of the cell Person) when the user clicks on the button.

当用户单击按钮时,将执行以下方法;

When the user clicks on the button the following method gets executed;

-(void) buttonOfCellClicked{
      // here i need to access the `Person` object that the user clicked
 }

我如何编写此代码?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

Person * person = [personsArr objectAtIndex:indexPath.row];

Person *person = [personsArr objectAtIndex:indexPath.row];

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell =  [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] ;

label = [[UILabel alloc]initWithFrame:CGRectMake(15, 5, 75, 60)];
label.text =person.firstName;   
[cell addSubview:label];
UIButton *button= [UIButton buttonWithType:UIButtonTypeRoundedRect];

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

[cell.contentView addSubview:button];


}

推荐答案

id findAncestor(UIView *view, Class class) {
    while (view && ![view isKindOfClass:class])
        view = [view superview];
    return view;
}

- (void)buttonOfCellClicked:(UIButton *)button
{
    UITableViewCell *cell = (UITableViewCell *)findAncestor(button, [UITableViewCell class]);
    UITableView *table = (UITableView *)findAncestor(cell, [UITableView class]);
    NSIndexPath *path = [table indexPathForCell:cell];
    if (!path)
        return;
    Person *person = [personsArr objectAtIndex:path.row];
    // do whatever with person
}

这篇关于在按钮上单击tableViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆