【问题标题】:SWIFT: Connect UITableViewCell to two different detail view controllersSWIFT:将 UITableViewCell 连接到两个不同的详细视图控制器
【发布时间】:2019-08-20 19:06:36
【问题描述】:

假设我有一个 SWIFT 应用程序,它包含一个带有表格的 UIViewController。该表当然有原型 UITableViewCells。单元格中包含的信息可以是两种内部对象类型之一,比如说 Widget 和 Sprocket。 Widget 和 Sprocket 是派生自同一个基类 Thing 的对象。

我的表格将是一个事物列表,其中每个事物要么是一个小部件,要么是一个 Sprocket。我想要发生的是,如果用户选择一个作为 Widget 的表格单元格,它应该显示一个 Widget 的详细信息 ViewController,即 WidgetViewController。但是,如果用户选择了 Sprocket,则应用程序应显示 SprocketViewController。

我究竟怎样才能做到这一点?我的理解是,如果我进入情节提要并单击拖动以从主 VC 到 WidgetViewController 或 SprocketViewController 进行转场,那么该转场将自动发生在应用程序中,即无需我添加任何代码。因此,如果我单击拖动以创建两个这样的 segue,那么我不知道会发生什么,但我认为应用程序会因尝试调用两个 segue 而崩溃。

我面临的问题是,我当前的应用程序有一个 WidgetTableViewController,其情节提要与 WidgetViewController 相接,还有一个 SprocketTableViewController,情节提要与 SprocketViewController 相接,但现在我必须将 Widgets 和 Sprocket 放入同一个 VC( ie ThingTableViewController) 并让应用有条件地启动 WidgetViewController 或 SprocketViewController。

那么我该怎么做呢?

【问题讨论】:

  • 对问题本身投了两次反对票?为什么?

标签: ios swift uitableview segue uistoryboardsegue


【解决方案1】:

一种方法可以是:

UITableViewDelegatetableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 函数中,检查所选单元格是否对应于对象Widget 或对象Sprocket

然后,使用此代码提供相应的UIViewController 和必要的配置:

let vc = UIStoryboard(name: "The name of your storyboard here", bundle: nil).instantiateViewController(withIdentifier: "Your VC identifier") as! YourViewController
// pass your data and configure the viewcontroller here
navigationController?.pushViewController(vc, animated: true)

在情节提要中,将您认为方便的标识符分配给您的ViewController

选择 ViewController -> 3rd item -> Identity -> StoryboardId 并勾选“Use Storyboard ID”

注意:删除你当前使用的segues

【讨论】:

    【解决方案2】:

    1) 要配置你的单元格,你有你的数据源。所以基本上你可以用这样的结构数组来配置你的 tableView。

    struct ViewModel { var type: CellType ... }

    当你用type点击你的单元格时,你可以很容易地找到你需要的细节控制器。

    2) 在didSelectRow 中,你冷被窃听了细胞

        let cell = tableView.cellForRow(at: indexPath)
    

    而不仅仅是检查它是 WidgetsCell 还是 SprocketsCell

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      相关资源
      最近更新 更多