【问题标题】:How to create clickable cells in UITableView (Swift)如何在 UITableView (Swift) 中创建可点击的单元格
【发布时间】:2019-11-07 10:59:13
【问题描述】:

我正在做一个个人项目,我想让 UITableView 中的单元格可点击,这样当它们被按下时,它们会转到下一个视图,并在按下时从它们的单元格中传递信息。

我尝试查看其他指南和视频来演示如何执行此操作,但它们都已过时。一个在我看来似乎很有希望但最终没有发挥作用的突出之处是参考了某个“didSelectRowAt”函数,但我无法让它发挥作用。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as!
    CandidateTableViewCell
    if (indexPath.row >= candidateCells.count){
        print("???")
        candidateCells.append(cell)
        print("Strange error")
    }
    tableView.delegate = self
    cell.CandidateName?.text = candidatesNames[indexPath.item]
    cell.CandidatePos?.text = candidatesPositions[indexPath.item]
    //cell.candidateButton.tag = indexPath.row
    cell.CandidateName.sizeToFit()
    cell.CandidatePos.sizeToFit()
    print(candidateCells)
    print(indexPath.row)
    print(candidateCells.count)
    print(indexPath.row >= candidateCells.count)
    candidateCells[indexPath.item] = cell
    return cell

}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "Segue", sender: Any?.self)
}

我期望发生的事情是该单元格将变为可点击,当点击该单元格时,它会将我发送到应用程序的下一页,但是当点击时,什么也没有发生。单元格不会突出显示,并且不会发生segue。非常感谢您的任何建议!

【问题讨论】:

标签: ios swift uitableview interactive


【解决方案1】:

如果您想将信息传递到下一个单元格,我通常会避免使用 Segue,并使用重用标识符设置 ViewController。通过这样做,您可以更轻松地传递信息。比如

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let vc = self.storyboard?.instantiateViewController(withIdentifier: "YOURRESUEIDENTIFIER") as! YOURVIEWCONTROLLERCLASS
        vc.infoToPass = cellData[indexPath.row]
        DispatchQueue.main.async {
            self.navigationController?.pushViewController(vc, animated: true)
        }

    }

您的另一个选择是实现shouldPerformSegueWithIdentifier() 方法以正确设置数据。您将单击您的单元格,该单元格调用performSegue 函数,该函数将调用shouldPerformSegueWithIdentifier,您可以在其中设置数据并返回true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多