swift tableview cell跳转问题。

如题,我想知道cell跳转的数据与我集合设置的数据相对应跳转 而不是 indexPath.row == 0。

阅读 3k
1 个回答

设置判断条件跳转啊。比如根据indexPath.row对应跳转,或者如果你觉得这样不方便优化的话,你可以给当页的功能设置对应的枚举,然后直接设置一个全局的元组数组,在cellForRowAt indexPath处判断元组的类型就行了。
类似这样:

let optionList:[(title:String,type:XXType)] = [
    ("title1",XXType.type1),
    ("title2",.Type2)
]

判断的时候根据optionList[indexPath.row].type判断就可以了。
像这种的方法很多,看自己需要去调整就行了。这个写法比较好的是方便随时更改tableview列表的内容,比较方便修改,要改的时候只需要把元组数组增删一下,然后再调用的地方对应做增删就可以,耦合比较低。

PS:枚举和元组可以了解一下。

附上一份完整代码:


enum MType {
    case type1
    case type2
    case type3
    case type4
    case type5
}

class ViewController: UIViewController {
    
    let cellID = "cellIdentifier"
    let optionList:[(title:String, type:MType)] = [
        ("title1", .type1),
        ("标题2", .type2),
        ("title3", .type3),
        ("title4", .type4),
        ("title5", .type5)]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.white
        
        let tableView = UITableView(frame: UIScreen.main.bounds, style: UITableView.Style.plain)
        
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellID)
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
        
    }
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return optionList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)
        
        let option = optionList[indexPath.row]
        cell.textLabel?.text = option.title
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let option = optionList[indexPath.row]
        
        print("cell's title:\(option.title),row:\(indexPath.row)")
        
        switch option.type {
        case .type1:
            //根据类型对cell进行对应操作
            print("one")
        case .type2:
            print("two")
        case .type3:
            print("3")
        case .type4:
            print("click")
        default:
            print("last")
        }
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题