tattiweb
tattiweb

Reputation: 21

Passing data to UIbutton in custom cell

I have a table view controller with custom cell. custom cell has got a button and some text label. How can i pass the text data of the row to the button when clicked?

Upvotes: 0

Views: 894

Answers (3)

peig
peig

Reputation: 418

Easy... add label text to button accessibilityValue and recover it in the target method.

{
    UIButton * button = [[UIButton alloc]init];
    button.accessibilityValue = label.text;
    [button addTarget:self action:@selector(sendLabelString:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)sendLabelString:(UIButton*)sender{
     NSString * labelString = sender.accessibilityValue;
}

Upvotes: 1

joker
joker

Reputation: 3752

The problem as I understand:

  1. You have custom cell with a UILabel and UIButton
  2. On click, you want the title of the button to be the same as that of the label

The answer to the problem as just described:

  1. You need to assign a tag to the label and the button so you can get a reference to them in the code. To do this:

    1.1. Go to the story board

    1.2. select the UILabel

    1.3. from the properties, you can find the tag property, give it a number (like 1 for instance)

    1.4. Go through 1.1 through 1.3 for the UIButton (give it tag number 2).

  2. in the table view controller (the .m class file), add the following code:

    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
        UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath]; // fetch an instance from the cell
        UILabel * lbl = (UILabel *) [cell viewWithTag: 1]; // fetch an instance of the label
        UIButton * btn = (UIButton *) [cell viewWithTag: 2]; // fetch an instance of the button
        btn.title = lbl.text; // I don't remember the text properties :D (figure it our yourself. it should be easy)
     }
    

Upvotes: 0

navroz
navroz

Reputation: 402

1)In your cellForRowAtIndexPath: , assign button tag as index

cell.yourbutton.tag = indexPath.row;

2) Add target and action for your button as below.

[cell.yourbutton addTarget:self action:@selector(yourButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

3) Code to action based on index as below in ViewControler.

-(void)yourButtonClicked:(UIButton*)sender{
 [arrayOfTextVaule objectAtIndex:sender.tag];}

OR

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
yourCustomCell *selectedCell=[tableView cellForRowAtIndexPath:indexPath];
NSLog(@"%@",selectedCell.label);}

Upvotes: 3

Related Questions