ios - 如何在自定义的tableViewController中转换到另一个viewController?

标签 ios objective-c uitableview

我正在通过 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 中的行时得到的结果: enter image description here

这是 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/

相关文章:

ios - Xcode 8 控制台垃圾?

javascript - react-native-scrollable-tab-view 上的无形边距

iphone - 无法更改 TextView 中的文本

ios - 如何从 iOS 中的 ALAsset 获取视频的缩略图?

ios - HealthKit 授权状态始终为 1

swift - 自调整单元格使 View 拉伸(stretch)

ios - 获取 UIslider 上的索引

ios - 每次我单击搜索栏时,ios应用程序崩溃,同时从parse.com中检索数据

ios - 没有调用 prepareForSegue 的 UITableView 到 UICollectionView

swift - 根据表格的可读宽度缩放 UITableViewCell 的高度