是否可以为每个UITableViewCell绑定对应的独立ViewController?
方案实现说明
该需求完全可以实现,以下是具体实现步骤和代码修改参考:
步骤1:创建对应功能的独立控制器
分别为三个计算功能创建各自的UIViewController子类,在每个控制器内部单独实现对应数量的输入框、计算逻辑和UI布局:
RuleOf72ViewController:实现72法则的1个输入框及对应计算逻辑FutureValueViewController:实现终值计算的4个输入框及对应计算逻辑SimpleInterestViewController:实现单利计算的输入框及对应计算逻辑
步骤2:在原有列表控制器中添加点击跳转逻辑
在你现有的ViewController类中实现UITableView的点击代理方法tableView(_:didSelectRowAt:),根据点击的行索引判断对应的功能,跳转至对应控制器即可。
修改后的完整代码如下:
class ViewController: UITableViewController { let functions = ["Rule of 72","Future Value", "Simple Interest"] override func viewDidLoad() { super.viewDidLoad() // 提前注册cell tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = self.functions[indexPath.row] return cell } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return functions.count // 这里建议直接用数组长度,后续加功能不用手动改数值 } // 新增点击跳转代理方法 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch indexPath.row { case 0: let vc = RuleOf72ViewController() navigationController?.pushViewController(vc, animated: true) case 1: let vc = FutureValueViewController() navigationController?.pushViewController(vc, animated: true) case 2: let vc = SimpleInterestViewController() navigationController?.pushViewController(vc, animated: true) default: break } } }
注意事项
- 确保你的列表控制器外层包裹了
UINavigationController,才能使用pushViewController的跳转方式,如果不需要导航栏跳转,也可以替换为present(_:animated:completion:)方法弹出控制器 - 如果你使用Storyboard搭建界面,也可以给每个功能控制器设置Storyboard ID,通过
instantiateViewController(withIdentifier:)方法初始化对应控制器即可
内容的提问来源于stack exchange,提问作者bigmanlar
相关产品推荐
相关产品推荐

