swift: didSelectRowAtIndexPath

2019-02-20 02:22发布

I have tableViewController. I want to click on 1 cell and get print("0") and click on 2 cell and get print("1")

But my code doesn’t work. Why?

import UIKit

class MasterViewController: UITableViewController {

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

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

// MARK: - Table view data source

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

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

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: String(format: "Cell%d", indexPath.row), for: indexPath)
    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    if indexPath.row == 0 {
        print("0")
    }

    else if indexPath.row == 1 {
        print("1")
        self.performSegue(withIdentifier: "detailSegue", sender: self)
    }

}

2条回答
Ridiculous、
2楼-- · 2019-02-20 02:31

In Swift 3 the signature of the method in an UITableViewController is

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
查看更多
趁早两清
3楼-- · 2019-02-20 02:48

It seem that you are trying to mix between Swift 3 and older version. Please change it to:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
查看更多
登录 后发表回答