UITableViewDelegate根据行有条件地执行didSelectRowAt

UITableViewDelegate根据行有条件地执行didSelectRowAt,uitableview,cocoa-touch,didselectrowatindexpath,Uitableview,Cocoa Touch,Didselectrowatindexpath,我感兴趣的是能够根据用户选择的行有条件地执行代码。是否有方法将标识符与cellForRowAt中的每一行(单元格)关联起来,以帮助区分在DidSelectRowAt委托中选择使用的行 是的。您使用DidSelectRowAt方法是正确的。如果表中有视图控制器,则视图控制器必须采用两个标准委托:UITableViewDataSource,UITableViewDelegate class ViewController: UIViewController, UITableViewDataSource

我感兴趣的是能够根据用户选择的行有条件地执行代码。是否有方法将标识符与cellForRowAt中的每一行(单元格)关联起来,以帮助区分在DidSelectRowAt委托中选择使用的行

是的。您使用
DidSelectRowAt
方法是正确的。如果表中有视图控制器,则视图控制器必须采用两个标准委托:
UITableViewDataSource
UITableViewDelegate

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var table: UITableView!
    let message:[String] = ["Hello", "World", "How", "Are", "You"]

    /* Table with five rows */
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    /*Have a simple table with cells being the words in the message */
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = message[indexPath.row]
        return cell
    }

    /*Optional method to determine which row was pressed*/
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        print("I'm row number "+String(indexPath.row))
    }

    /*set the table's delegate and datasource to the view controller*/
    override func viewDidLoad() {
        super.viewDidLoad()
        self.table.delegate = self
        self.table.dataSource = self
    }
}

这将产生:
我是第一排

回想一下索引是从零开始的。

我已经有了这个功能-很抱歉没有发布我目前拥有的功能(它相当广泛)。我想知道是否有办法将cellForRowAt上显示的内容关联起来,然后能够在didSelectRowAt中被引用。例如,如果我单击该行,该行显示“Hello”,则执行一件事,如果该行显示“World”,则执行另一件事。@Kevin一种方法是简单地使用switch语句来处理
indexPath.row
方法中的
DidSelectRowAt
内容,并调用对应于该行的相应函数。indexPath.row中包含哪些值?据我了解,我认为这只是选择的行号。是否有与indexPath.row关联的更多信息?是的,通过使用行号在数据源中查找适当的条目。