2013-11-26 33 views
0

我正在通過uitableviewcell的子類自定義表格視圖單元格。那麼,如何在單元格被觸摸時從這個視圖控制器轉移到另一個視圖控制器?謝謝。如何在自定義的tableViewController中轉移到另一個viewController?

看來,在執行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]; 

} 
+0

什麼是您的自定義表格視圖單元格的控件???這些表格視圖單元格內的那些控件是否需要觸摸事件? –

+0

具體而言_what_不起作用?感謝您發佈您的代碼,這有幫助,但是當您選擇表格視圖單元格時會發生什麼? –

回答

1

我的猜測:您的didSelect方法被調用,但您的SecondViewController是nil。給你的新控制器一個標識符在你的故事板,並做

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

否則你的控制器只是空的,因爲它沒有連接到故事板。事實上,只有故事板知道你的自定義類存在,而不是相反。

如果你不使用的故事板,初始化你SecondViewController與initWithNibName:bundle:,而不是...,並把新的init()方法在你的舊..所以init電話initWithNibName:bundle:內部。這樣,沒有人需要知道你的xib文件的名字,而且代碼要短得多。

0

這是tableView的委託方法,將在您點擊一個單元格時自動調用。

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

如果使用要運輸的任何uicontrols那麼你需要添加selector方法和過渡添加代碼存在或觸摸事件,你可以從uitableViewdelegate方法didSelectRowAtIndexPath過境

相關問題