【问题标题】:Trigger segue from UITableView without Controller从没有控制器的 UITableView 触发 segue
【发布时间】:2015-10-20 00:38:45
【问题描述】:

我有一个 UITableView 类,我放置在多个 ViewController 中。

当用户 didSelectRowAtIndexPath 时,我想转至另一个 ViewController。

但是,由于 UITableView 类是独立的,我无法以编程方式从该类触发 segue,因为 self.performSegueWithIdentifierself.showViewController 中的 self 指的是 UITableView。

我知道应该由 ViewControllers 负责 segues,但我无法从给定的 ViewController 访问 didSelectRowAtIndexPath(因为它不管理 UITableView)。

如何从不继承自 ViewController 的 UITableView 中分离?

【问题讨论】:

    标签: ios swift uitableview uiviewcontroller segue


    【解决方案1】:

    您需要一种方法来告诉视图控制器表视图上的一行已被选中,以便视图控制器可以执行转场。

    委托是实现这种通信的好方法。

    1. 定义一个委托协议。

       protocol TableRowSelectionDelegate: class {
           func tableRowSelected(rowValue: String)
       }
      
    2. 在表格视图类中定义一个委托变量。

      var tableRowSelectionDelegate: TableRowSelectionDelegate?
      
    3. In your table view class, when the table row is selected, call the delegate, passing the row value (i.e., data from your model that corresponds to the selected index path).使用可选的 ?运算符,这样如果没有设置委托,就不会发生任何不好的事情。

      tableRowSelectionDelegate?.tableRowSelected(rowValue)
      
    4. 将协议添加到您的视图控制器。

      class ViewController: UIViewController, TableRowSelectionDelegate
      
    5. 在您的视图控制器中,将其设置为您的表视图类的委托。

      tableViewClass.tableRowSelectionDelegate = self
      
    6. 在您的视图控制器中实现协议。

      func tableRowSelected(rowValue: String) {
          //perform the segue here...
          //  if necessary, pass the row value to the destination
          //  view controller before performing the segue
      }
      

    这个委托协议现在可以由使用您的表视图类的所有视图控制器实现,并且每个视图控制器都可以根据需要进行响应。也许你不会总是想继续。让代表决定。

    【讨论】:

    • 你不觉得有一种不那么老套的方法吗?
    • 根本不是一种骇人听闻的方式。祝你好运。
    【解决方案2】:

    首先,我想推荐苹果的文档Adding a Segue Between Scenes in a Storyboard

    您肯定将您的 UITableView 放在视图控制器上,并在故事板上设置 UITableViewDelegate、UITableViewDataSource,以便您的视图控制器可以知道用户选择了哪一行。

    【讨论】:

      猜你喜欢
      • 2011-12-22
      • 2012-12-09
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      • 2012-08-30
      • 1970-01-01
      相关资源
      最近更新 更多