如何在单击按钮上获取UITableviewcell(自定义单元格)值

use*_*389 5 objective-c uitableview ios

我有一个UITableViewCell(自定义单元格),我在其中创建一些按钮和文本字段,并为按钮和文本字段分配标签.但是我无法在点击按钮上获得按钮标题和文本字段值.

cellForRowAtIndexPath

`[((CustomCell *) cell).btn setTag:rowTag];
 [((CustomCell *) cell).textField2 setTag:rowTag+1];`

-(IBAction)submitBtnAction:(UIControl *)sender
{
    for (int i=0; i<[self->_dataArray count]; i++)
    {
        NSIndexPath *myIP = [NSIndexPath indexPathForRow:i inSection:0];
        NSLog(@"myIP.row %d",myIP.row);
        UITableViewCell *cell = [tblView1 cellForRowAtIndexPath:myIP];
        NSLog(@"tag %d",cell.tag);
        UIButton *btn = (UIButton *)[cell.contentView viewWithTag:i];
        NSLog(@"btn text %@, tag %d",btn.titleLabel.text,btn.tag);
        UITextField *tf = (UITextField *)[cell.contentView viewWithTag:i+1];
        NSLog(@"tf text %@, tag %d",tf.text,btn.tag);

    }
}
Run Code Online (Sandbox Code Playgroud)

我收到这样的错误

-[UITableViewCellContentView titleLabel]: unrecognized selector sent to instance 0x71844e0
2013-07-17 13:48:29.998 Text[1271:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITableViewCellContentView titleLabel]: unrecognized selector sent to instance 0x71844e0'
Run Code Online (Sandbox Code Playgroud)

Ama*_*mar 11

我认为你可以直接访问你的单元格btntextField2属性cellForRowAtIndexPath:.假设您正在创建并返回实例CustomCell,只需将其强制转换为CustomCell而不是UITableviewCell.见下面的修改代码

-(IBAction)submitBtnAction:(UIControl *)sender
{
        UIButton *button = (UIButton*)sender;
        NSIndexPath *myIP = [NSIndexPath indexPathForRow:sender.tag inSection:0];
        //Type cast it to CustomCell
        CustomCell *cell = (CustomCell*)[tblView1 cellForRowAtIndexPath:myIP];
        UIButton *btn = cell.btn;
        NSLog(@"btn text %@, tag %d",btn.titleLabel.text,btn.tag);

        UITextField *tf = cell.textField2;
        NSLog(@"tf text %@, tag %d",tf.text,btn.tag);
}
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!