我有一个UITableViewController与UIViewController连接。
我创建了一个全局counter来跟踪在UITableView中选择了哪一行。因为根据选择的行,显示的UIViewController中的某些信息将更改。
我认为整理它是可能的,这样dayx段只需调用一次,counter就可以根据选择的行进行相应的更改?但我想不通。
这就是我现在拥有的,它可以工作,但看起来很凌乱?:

//what happens when row is selected
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.row == 0 {
        counter = 0
        self.performSegue(withIdentifier: "dayx", sender: self)
    } else if indexPath.row == 1 {
        counter = 1
        self.performSegue(withIdentifier: "dayx", sender: self)
    }
    else if indexPath.row == 2 {
        counter = 2
        self.performSegue(withIdentifier: "dayx", sender: self)
    }
    else if indexPath.row == 3 {
        counter = 3
        self.performSegue(withIdentifier: "dayx", sender: self)
    }
    else if indexPath.row == 4 {
        counter = 4
        self.performSegue(withIdentifier: "dayx", sender: self)
    }
    else if indexPath.row == 5 {
        counter = 5
        self.performSegue(withIdentifier: "dayx", sender: self)
    }
    else if indexPath.row == 6 {
        counter = 6
        self.performSegue(withIdentifier: "dayx", sender: self)
    }
}

最佳答案

使用flatMap
斯威夫特4.0

indexPath.flatMap {
    print($0)
    counter = $0
    self.performSegue(withIdentifier: "dayx", sender: self)
}

稍后:
let _ = indexPath.compactMap {
     counter = $0
     self.performSegue(withIdentifier: "dayx", sender: self)
 }

了解flatMap的基本知识。阅读本文Replacing flatMap With compactMap
更新
如果所有行都打算执行performSegue。简单:
//what happens when row is selected
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

   counter = indexPath.row
   self.performSegue(withIdentifier: "dayx", sender: self)
}

关于swift - 试图找出使用单个UITableview的一种不太笨拙的方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54943006/

10-10 21:33