简体   繁体   中英

Table View Cell in external nib. Storyboards

So I have been building a table view in storyboard and I created an external Nib file with my custom UITableViewCell. Everything is working great. However, there is a button on the table view cell that I would like to have connected to a view in the storyboard, via a segue. Now I'm still very new to all this, so how would I connect the button on the custom cell to the view controller in the storyboard? Have I gone about this completely wrong? If so, how would I restructure my project quickly and easily? I would be grateful if you could provide a little explanation so I can learn from this.

Thanks for any help,
Regards,
Mike

It is possible to set a button inside UITableViewCell in storyboard using story board. I have done similar thing before. So, here's a solution;

  • Create prototyoe cell inside UITableView cell and add a UIButton to it.
  • Create a segue from the button to a new view controller and then choose the modal or push.

Now, in the UITableViewData datasource cellForRowAtIndexPath;

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    UIButton *button = ((UIButton*)[cell.contentView.subviews objectAtIndex:0])
    button.tag = indexPath.row;
    cell.textLabel.text = @"Hello Text"
    ;
    return cell;
}

Now, when your button is clicked your prepareForSegue: is called.

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"identifier"]){
        UIButton *button = (UIButton*)sender;
        NewViewController *viewController = [segue destinationViewController];
       if(button.tag == 1)
          viewController.someobject = ...
       else 
          viewController.somobject = ...
    }
}

And that should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM