Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get UITableviewcell(custom cell) values on click on button

I have a UITableViewCell(Custom cell) in which i am creating some buttons and textfields and assigning tags to the buttons and textfields. But i couldn't get button title and textfield values on click on button.

In 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);

    }
}

I'm getting error like this

-[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'
like image 449
user1831389 Avatar asked Jul 17 '13 08:07

user1831389


2 Answers

I think you can directly access the btn and textField2 properties of your cell, once you get it from cellForRowAtIndexPath:. Assuming you are creating and returning instance of CustomCell, just typecast it to CustomCell instead of UITableviewCell. See modified code below

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

Hope that helps!

like image 87
Amar Avatar answered Nov 09 '22 15:11

Amar


Simple way to do it:

-(IBAction)submitBtnAction:(UIControl *)sender
{
   UIButton *senderButton = (UIButton *)sender;

    NSIndexPath *myIP = [NSIndexPath indexPathForRow:i inSection:0];

    CustomCell *cell = (CustomCell*)[tblView1 cellForRowAtIndexPath:myIP];

    NSLog(@"cell.textField -tag :%d",cell.textField2.tag);

    NSLog(@"cell.btn -tag :%d",cell.btn.tag);

}
like image 2
Satheesh Avatar answered Nov 09 '22 16:11

Satheesh