【问题标题】:Getting an input onclick in UITableView在 UITableView 中获取输入 onclick
【发布时间】:2018-02-25 11:37:18
【问题描述】:

当用户点击 UITableView 的单元格时,我正在尝试获取输入。这是我的代码:

import UIKit

class TableView: UIViewController, UITableViewDataSource {

    public var data = Array<Array<String>>()

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier")!
        cell.textLabel?.text = data[indexPath.row][0]
        cell.detailTextLabel?.text = data[indexPath.row][1]
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("TEST")
    }

}

在 ViewController 我有:

...


let tvClass = TableView()

override func viewDidLoad() {
    super.viewDidLoad()
    tvClass.data = [["title", "name"]]
    self.tableView.dataSource = tv
    self.tableView.alwaysBounceVertical = false
}


...

为什么我在单击单元格时没有收到“TEST”?

【问题讨论】:

  • 你错过了委托 self.tableView.delegate = self

标签: ios swift tableview didselectrowatindexpath


【解决方案1】:

didSelectRowAtUITableViewDelegate 中的一个方法,所以,在viewDidLoad 中像这样设置表委托

self.tableView.delegate = self;

并像这样更改类声明

class TableView: UIViewController, UITableViewDataSource , UITableViewDelegate {

【讨论】:

  • 我想你想说self.tableView.delegate = tvClass。对吗?
  • 谢谢。现在我在print(test) 之后添加了这个:let test = self.storyboard?.instantiateViewController(withIdentifier: "ViewTest") as! ViewTest,然后是self.navigationController?.pushViewController(test, animated: true)。你知道我为什么会出错吗?
  • 嗯,它正在打印TEST,但它不会改变视图。错误是Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
  • 确保情节提要 id 是 viewController ViewTest 的 ViewTest
  • 是的,它是正确的,但错误仍然存​​在。为什么?
【解决方案2】:

唯一缺少的是

TableView 委托。

代理告诉 iOS sdk 知道正在执行操作。

self.tableView.delegate = self

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多