我正在尝试开发一个 TableView Controller ,其中行连接到多个 View Controllers
(TextField、TextView、TableView、DatePicker、ImageView 等)。
所以如果我点击任何一行,它应该打开 Intermediate View
并将适当的 Controller 放在一个公共(public)位置,所有 Controller 的其余部分都是相同的。假设我点击了一个索引映射到 TableView 的行。当它打开中间 Controller 时,它应该将 tableview 放在公共(public)容器中,这个 table view 应该来自所有其他 Tableview 的单个 TableView Controller 。
我是 ios 的新手,不会设计这个。
设计这个的最佳方法是什么?我该如何实现?
谢谢
最佳答案
我建议不要在 Storyboard 中创建单元格并连接它。而是在 Storyboard 中保留空表并使用代码创建单元格。您可以通过继承 UITableViewCell
来创建自定义单元格。
在 Storyboard 中,您只需使用 segue 将 TableView 与所有 View Controller 链接起来,并为其指定正确的标识符名称。
现在实现UITableView
的所有委托(delegate)方法。覆盖 -tableView:didSelectRowAtIndexPath:
方法并在行选择上对特定行执行 segue。
示例:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
switch (indexPath.row) {
case 0:
[self performSegueWithIdentifier:@"BasicCoreDataSegue" sender:self];
break;
default:
break;
}
}
在上面的例子中,如果您选择第一行,它将推送与 Storyboard 中的 BasicCoreDataSegue
segue 连接的 View Controller ,您可以将其与图像进行比较。
使用类似的方式创建其他 segues 并在不同 switch case 的 didSelectRowAtIndexPath
方法中调用它们。
此外,如果您想将任何值传递给推送 Controller ,请覆盖以下方法:
- (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";
}
}
编辑:
以上代码适用于普通 Controller 。现在您不需要在 didSelectRowAtIndexPath
方法中创建更多的 segues set Intermediate controller segue。
使用[self.tableView indexPathForSelectedRow]
方法在prepareForSegue
方法中获取选定的行。
例如:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self performSegueWithIdentifier:@"BasicCoreDataSegue" sender:self];
}
现在,当 prepareForSegue
被调用时,然后为中间 Controller 设置整数值。
- (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()
的中间 Controller 中使用 switch case 从行选择中获取您想要的 Controller 对象,并将其 View 作为 subview 添加到中间 Controller 中。
UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard"
bundle: nil];
TextViewController *controller = (TextViewController*)[storyBoard
instantiateViewControllerWithIdentifier: @"TextViewControllerId"];
[self.topView addSubview:controller.view];
关于ios - Table View Controller 每行连接到不同的 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27775630/