首页 > 解决方案 > 我想使用 didSelectRowAt 将数组从 UITableView 显示到下一个 viewController

问题描述

我希望quizNumber返回quizNumberArray取决于选择的单元格。

例如,如果用户选择了第一个单元格,则quizNumber返回 1

在 UITableViewController 内部

let quizNumberArray = [1,2,3,4,5,6,7,8,9,10]
    var quizNum = Int()

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let vc = storyboard?.instantiateViewController(withIdentifier: "toQuestionVC") as? QuestionVC
    quizNum = quizNumberArray[indexPath.row]
}
    override  func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let identifier = segue.identifier {
        if identifier == "toQuestionVC" {
            let questionController = segue.destination as! QuestionVC
            questionController.quizNumber = quizNum
}

在下一个 ViewController

class QuestionVC : UIViewController {
    var quizNumber = Int()
    func updateQuestion(){
        if quizNumber == 1 {
            //.....
        }
    }
}

quizNumber返回 0。

标签: iosarraysswiftuitableview

解决方案


试试这个代码:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     let vc = storyboard?.instantiateViewController(withIdentifier: "toQuestionVC") as? QuestionVC
     vc?.quizNumber = quizNumberArray[indexPath.row]
     navigationController?.pushViewController(vc!, animated: true)

}

并删除 segue 以运行上述代码


推荐阅读