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

时间:2013-11-26 07:32:56

标签: ios objective-c uitableview

我正在通过uitableviewcell的子类自定义表视图单元格。那么,当触摸单元格时,如何从该视图控制器转移到另一个视图控制器?感谢。

似乎在 tableview: didSelectRowAtIndexPath: 中执行此操作无效。这是我的代码:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SecondViewController *anotherViewController = [[SecondViewController alloc] init];
    [[self navigationController] pushViewController:anotherViewController animated:YES];
}

当我按下表格视图中的行时,这就是我所得到的: 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];

 }

3 个答案:

答案 0 :(得分:1)

我的猜测:你的didSelect方法被调用,但你的SecondViewController是nil。在故事板中为新控制器提供标识符并执行

SecondViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"Second"];

否则你的控制器只是空的,因为它没有连接到故事板。事实上,只有故事板知道您的自定义类存在,而不是相反。

如果您不使用故事板,请使用initWithNibName:bundle:初始化您的SecondViewController ...并将新的init方法放在旧的方法中......所以init在内部调用initWithNibName:bundle:。这样,没有人必须知道你的xib文件的名称,而且代码要短得多。

答案 1 :(得分:0)

这是tableView的委托方法,在点击单元格时会自动调用。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}

答案 2 :(得分:0)

如果使用想要转移任何uicontrols的触摸事件,那么您需要添加selector方法并添加转换代码,或者您可以从uitableView {{1}转换方法delegate