didSelectRowAtIndexpath不响应点击

时间:2019-04-01 08:01:44

标签: swift uitableview

我正在为高中生制作一个修订版应用程序。在此视图中,用户应该能够选择他们要针对某个主题学习的单元,并且所选单元的索引路径将存储在一个int数组中,并传递到下一个用于显示图像的视图。不幸的是,didSelectRowAt方法由于某种原因没有响应。

正确设置了委托和数据源,我知道在我在函数中编写打印语句时未调用它,并且在单击任何一个表格单元格时控制台中均未打印任何内容。

var units = [String]()
var selectedRows = [Int]()

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return units.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "unitCell", for: indexPath) as! UnitCell
    cell.textLabel?.text = units[indexPath.row]
    return cell
}

func tableView(tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedRows.append(indexPath.row)
    print(selectedRows)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destination = segue.destination as! ImageView
    destination.folderNames = selectedRows
}

我期望所选单元格的行索引为int数组。但是现在它只是空的。

3 个答案:

答案 0 :(得分:1)

如果您在问题中显示的代码正确,则didSelectRowAt方法的签名不正确。应该是:

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

请注意第一个参数的前导“ _”。如果您的类是UITableViewController,则还需要添加一个override关键字。

如果您的代码已在使用此签名,请更新您的问题以反映这一点。

此外,此前置代码也不正确。请将其更新为您实际使用的

var units = String var selectedRows = Int

答案 1 :(得分:0)

您应该使用delegate method

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

代替您现有的

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath)

尝试并分享您的结果。

答案 2 :(得分:0)

  • 第一件事是您的 didSectRow 被描述,因此请使用 低于一个

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    
  • 其次,您必须像下面一样将TableView委托设置为Self

    tableView.delegate = self
    
相关问题