0

I have a view controller in that having a table view in that a Custom cell.

I have a button in a custom cell

MyViewController
---View
------TableView
-------------Custom cell
-------------------UIButton

I want to implement the button action for that button in the custom cell, in the Custom cell class.

I want to present another viewcontoler called mailPage by clicking on button for thet

-(IBAction)webButtonClicked:(id)sender
{
  [self presentModalViewController:mailpage animated:YES];
}

But here self means CustomCell, even i tried with superview i didn't get my view contoller to represent in place of self

I tried like this but no use.

MyViewController *myViewController =self.superview 

How to get my View controler containing the current custom cell

Cezar
  • 55,636
  • 19
  • 86
  • 87
user2492409
  • 73
  • 10

3 Answers3

4

I would strongly recommend you place your view controller presentation logic in a view controller, rather than a UITableViewCell.

As you're already using a custom cell, this will be fairly straightforward. Simply define a new protocol for your custom cell, and have your view controller act as a delegate. Or alternatively, as per this answer here you can forgo the delegate entirely, and simply have your view controller act as the target for your button.

Your custom UITableViewCell really shouldn't have any dependencies or knowledge of the view controller it's being displayed in.

Community
  • 1
  • 1
lxt
  • 31,146
  • 5
  • 78
  • 83
2

well the easy way is to set an unique tag for the button in the cell and in cellForRowAtIndexpath method you can get the button instance as

UIButton *sampleButton=(UIButton *)[cell viewWithTag:3]; 

and set the action as

    [sampleButton addTarget:self action:@selector(sampleButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

and set up the action in the viewcontroller

-(void)sampleButtonPressed:(id)sender
{
}
Lithu T.V
  • 19,955
  • 12
  • 56
  • 101
2

try this:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"OpenHouseListCustomCell";
    OpenHouseListCustomCell *cell = (OpenHouseListCustomCell *)[tblOpenHouses dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil) {
        NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"OpenHouseListCustomCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        cell.showsReorderControl = NO;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor=[UIColor clearColor];
        [cell.btn1 addTarget:self action:@selector(ButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    }

    cell.btn1.tag = indexpath.row;
    return cell;
}

-(void) ButtonClicked {
    //your code here...
}
DharaParekh
  • 1,730
  • 1
  • 10
  • 17