Reputation: 21
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
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
Reputation: 3752
The problem as I understand:
The answer to the problem as just described:
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).
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
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