Reputation: 2825
I am customising the table view cell by a subclass of uitableviewcell. So, how can I transit from this view controller to another when the cell is touched? Thanks.
It seems that doing the implementation in tableview: didSelectRowAtIndexPath:
doesn't work. Here is my code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
SecondViewController *anotherViewController = [[SecondViewController alloc] init];
[[self navigationController] pushViewController:anotherViewController animated:YES];
}
This is what I got when I press the row in the table view:
And this is the code in myCell.m (my customised cell):
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.mainLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 180, 30)];
self.mainLabel.font = [UIFont systemFontOfSize:14.0];
[self.contentView addSubview:self.mainLabel];
self.mainButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.mainButton.frame = CGRectMake(190, 5, 100, 30);
[self.mainButton addTarget:self action:@selector(logButton:) forControlEvents:UIControlEventTouchUpInside];
[self.contentView addSubview:self.mainButton];
}
return self;
}
- (void)logButton:(UIButton *)sender{
NSLog(@"index path: %ld", (long)sender.tag);
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
}
Upvotes: 0
Views: 149
Reputation: 6190
My guess: Your didSelect
method gets called but your SecondViewController is nil
. Give your new controller an identifier in your storyboard and do
SecondViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"Second"];
Otherwise your controller is just empty, because it's not connected to the storyboard. In fact, only the storyboard knows that your custom class exists, not the other way round.
If you don't use storyboard, init your SecondViewController with initWithNibName:bundle:
instead... and put that new init method in your old one.. so init
calls initWithNibName:bundle:
internally. This way no one has to know the name of your xib file and the code is much shorter.
Upvotes: 1
Reputation: 12023
if use want to transit on the touch event of any uicontrols
then you need to add selector
methods and add code for transition there or you can transit from uitableView
delegate
method didSelectRowAtIndexPath
:
Upvotes: 0
Reputation: 950
This is the delegate method of tableView and will called automatically when you tap a cell.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}
Upvotes: 0