我正在通过 uitableviewcell 的子类自定义表格 View 单元格。那么,当单元格被触摸时,如何从这个 View Controller 转换到另一个 View Controller 呢?谢谢。
似乎在 tableview: didSelectRowAtIndexPath:
中实现不起作用。这是我的代码:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
SecondViewController *anotherViewController = [[SecondViewController alloc] init];
[[self navigationController] pushViewController:anotherViewController animated:YES];
}
这是当我按下 TableView 中的行时得到的结果:
这是 myCell.m(我的自定义单元格)中的代码:
- (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];
}
最佳答案
我的猜测:您的 didSelect
方法被调用,但您的 SecondViewController 为 nil
。在 Storyboard中为您的新 Controller 提供一个标识符,然后执行
SecondViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"Second"];
否则你的 Controller 就是空的,因为它没有连接到 Storyboard。事实上,只有 Storyboard知道您的自定义类存在,而不是相反。
如果您不使用 Storyboard,请使用 initWithNibName:bundle:
初始化 SecondViewController...并将新的 init 方法放入旧的 init 方法中...所以 init
在内部调用 initWithNibName:bundle:
。这样一来,任何人都不必知道您的 xib 文件的名称,并且代码也会短得多。
关于ios - 如何在自定义的tableViewController中转换到另一个viewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20211027/