【问题标题】:Swift adding clickable tableviewSwift添加可点击的tableview
【发布时间】:2018-07-20 13:25:48
【问题描述】:

当我创建一个 tableview 时,我无法点击我放在 tableview 上的任何项目。我想知道如何创建一个可以单击每个项目的表格视图,并且当用户单击一个项目(例如城市名称)时,它将用户重定向到不同的视图控制器。 (例如如果tableview中有22个可点击的item,那么总共会有22个新的不同的viewcontrollers) 非常感谢您!

【问题讨论】:

  • 你试过什么?你实现 UITableViewDelegate 了吗?
  • 您需要使用tableView:didSelectRowAtIndexPath: 方法。如果您使用 Master Detail 模板启动一个新的 xcode 项目,那么样板代码就是这样做的。
  • 这里是tableview的演示项目github.com/paresh1994/ProtocolDelegation-

标签: swift uitableview uiviewcontroller


【解决方案1】:

UITableViewDataSource 必须包含三个主要功能才能使表格视图与用户交互正常工作(例如,按下每一行)。这些功能是:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)

您要使用的功能是第三个。当用户通过在屏幕上点击它来选择某一行时调用它。您可以使用 'indexPath' 找出行索引。

如果您想使用 22 个不同的视图控制器,您需要在每个控制器之间手动创建一个 segue 并相应地标记它们。然后,您可能希望根据在第三个函数中选择的行来调用每个单独的 segue!您可以使用 performSegue() 函数调用带有标识符的 segue。

请注意,包含这些函数的类必须是 UITableViewDataSource 类型,并且您应该在 ViewDidLoad() 函数中告诉表格视图它是数据源,如下所示:

tableView.dataSource = self

【讨论】:

    【解决方案2】:

    下面是一个简单的代码:

    import UIKit
    class viewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
        @IBOutlet weak var tableView: UITableView!
        var identifiers = [String]()
    
        override func viewDidLoad() {
    
            // fill your identifiers here
    
            tableView.delegate = self
            tableView.dataSource = self
    
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
            return 22
        } 
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
            let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellIdentifier") as! yourCell
            // fill your cell's data in here
            return cell
        }
    
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
    
            // here you can use someThing like an array of your segue identifiers
            self.performSegue(withIdentifier: identifiers[indexPath.row], sender: self)
            //Or you can just implement a switch with every case doing what you want that cell to do which i don't recommend if you have 22 rows 
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 2019-04-17
      • 2017-01-04
      • 2020-11-28
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      相关资源
      最近更新 更多