如何在原型单元格中向UIButton添加方法?

时间:2012-10-26 14:04:50

标签: uitableview prototype

我正在创建一个包含两个原型单元格的表。按钮“Cell One”连接到方法 btnCellOneTouched ,按钮“Cell Two”连接到 btnCellTwoTouched 。每个原型单元格中的按钮标记为0,文本字段标记为1。

每个原型单元都有自己的标识符 - cellOne cellTwo 。这是我的 .m 文件中的代码。变量都是正确的,没有错误。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    intNumRows = 0;
    numSections = 1;
}

- (NSInteger)numberOfSectionsInTableView: (UITableView *)tableView
{
    return numSections;
}

- (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
    return intNumRows;
}

- (void)displayRowNum:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    NSLog(@"%d", btn.tag);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCellType];
    if(cell == nil)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCellType];

    [(UIButton *)[cell viewWithTag:0] addTarget:self action:@selector(displayRowNum:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

- (IBAction)btnCellOneTouched:(id)sender
{
    strCellType = @"cellOne";
    intLastRow = [tblMain numberOfRowsInSection:0];
    indexPath = [NSIndexPath indexPathForRow:intLastRow inSection:0];
    intNumRows++;
    [tblMain insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
}
- (IBAction)btnCellTwoTouched:(id)sender
{
    strCellType = @"cellTwo";
    intLastRow = [tblMain numberOfRowsInSection:0];
    indexPath = [NSIndexPath indexPathForRow:intLastRow inSection:0];
    intNumRows++;
    [tblMain insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
}

我收到错误因未捕获的异常而终止应用'NSInvalidArgumentException',原因:' - [UITableViewCell addTarget:action:forControlEvents:]:无法识别的选择器发送到实例0x90638e0'当我运行程序

我在运行时创建的单元格中为按钮指定方法的方式有什么问题?

如果我注释掉我添加目标的行,它可以正常工作。

这个让我感到困惑了一段时间。请帮忙。

谢谢, Anjaan。

0 个答案:

没有答案