我建议不要在情节提要中创建单元格并连接它。相反,在故事板中保留空表并使用代码创建单元格。您可以通过子类化来创建自定义单元格UITableViewCell
.
在故事板中,您只需使用 segue 将表视图与所有视图控制器链接起来并给予适当的标识符名称.
![enter image description here](https://i.stack.imgur.com/r0BDY.png)
现在实现所有委托方法UITableView
。覆盖-tableView:didSelectRowAtIndexPath:
方法并在行选择时对特定行执行 segue。
Example:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
switch (indexPath.row) {
case 0:
[self performSegueWithIdentifier:@"BasicCoreDataSegue" sender:self];
break;
default:
break;
}
}
在上面的情况下,如果您选择第一行,它将推送与之连接的视图控制器BasicCoreDataSegue
故事板中的segue,您可以将其与图像进行比较。
使用类似的方式创建其他segue并调用它们didSelectRowAtIndexPath
不同开关情况下的方法。
另外,如果您想将任何值传递给推送控制器,请重写以下方法:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if ([[segue identifier] isEqualToString:@"BasicCoreDataSegue"]) {
// Get reference to the destination view controller
TextViewController *vc = [segue destinationViewController];
vc.textView.text = "Hello";
}
}
Edit:
上面的代码适用于普通控制器。现在你也不需要创建更多的seguesdidSelectRowAtIndexPath
方法集中间控制器segue。
Use [self.tableView indexPathForSelectedRow]
获取所选行的方法prepareForSegue
method.
例如:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self performSegueWithIdentifier:@"BasicCoreDataSegue" sender:self];
}
现在,当prepareForSegue
调用然后为中间控制器设置整数值。
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// You can get selected row using below line
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
// Pass the selected object to the new view controller.
if ([[segue identifier] isEqualToString:@"BasicCoreDataSegue"]) {
// Get reference to the destination view controller
IntermediateController *vc = [segue destinationViewController];
vc.selectedIndex = indexPath.row;
}
}
在上面的代码中selectedIndex
是一个整数变量,用于跟踪选择了哪一行。
现在在中间控制器中-viewDidLoad()
使用 switch case 从行选择中获取所需的控制器对象,并将其视图添加为中间控制器中的子视图。
UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard"
bundle: nil];
TextViewController *controller = (TextViewController*)[storyBoard
instantiateViewControllerWithIdentifier: @"TextViewControllerId"];
[self.topView addSubview:controller.view];