尝试找出使用单个UITableview的笨拙方法

时间:2019-03-01 10:45:43

标签: swift uitableview swift4 didselectrowatindexpath

我有一个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)
    }
}

1 个答案:

答案 0 :(得分:1)

使用flatMap

Swift 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)
}