-3

How can I pass data from a cell by pressing a button in the same cell. Lets say I have a table with 3 cells row, each cell has a label with different value. What I need is when I press the button in cell 2 pass that value to another ViewController. Passing the data between controller is not problem when I press on the cell it's self, but my problem is when I press the specific button and hold the value of some string from that cell.

Thanks

Ahmed.S.Alkaabi
  • 243
  • 2
  • 10
  • "my problem is when I press the button" But _what_ is your problem when you press the button? You haven't explained what the trouble is. What is it that you don't know how to do? You know how to configure a button and respond when it is pressed, right? So what _don't_ you know? – matt Aug 24 '15 at 00:20
  • just few hours ago I posted this answer about how to associate a cell's button withe the data from the datasource. you should be able to adapt it. http://stackoverflow.com/questions/32170095/how-to-access-uitableview-from-within-uitableviewcell-in-swift/32170265#32170265 – vikingosegundo Aug 24 '15 at 00:22

1 Answers1

0

You have to delegate button action to controller. You should research it yourself but I'm gonna give you short example.

Let's assume you have a UITableViewCell , and of course UITableView has its own delegate methods like

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath

these are selection of a cell, but you want to control a button action. So you have a button inside cell like this

    UIButton *someButton = [[UIButton alloc] initWithFrame:CGRectMake(0,0, 50, 50)];
    [someButton addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:someButton];

this is in your cell class.

and .h of your cell you write delegation like this.

@protocol SomeProtocol <NSObject>

- (void) buttonPressedInCell:(NSString *) data;

@end

and your delegate property in .h

@property (nonatomic, strong) id<SomeProtocol> delegate;

and your cell.m

finally you can give delegate to your button action

- (void) buttonClicked {
    [delegate buttonPressedInCell];
}

so after this you can delegate this object whenver you want, in your case you want to give it to your UITableView let's do it.

you have like a CustomTableViewCell

and your controller you must yourController<SomeProtocol>

and you have to delegate your cell like yourCell.delegate = self;

then implement your delegate method

- (void) buttonPressedInCell:(NSString *) data {
    // do something like pushing new controller 
    //your data is in your controller now
}

Hope this helps you.

More information about delegation here

Gürhan KODALAK
  • 570
  • 7
  • 20