代码之家  ›  专栏  ›  技术社区  ›  Anvil

如何用prepareForSegue从2d数组中传递值

  •  0
  • Anvil  · 技术社区  · 8 年前

    我有一个这样的阵列 tableView :

    var array: [[String]] = [["Apples", "Bananas", "Oranges"], ["Round", "Curved", "Round"]]
    

    我想在按下单元格时传递单元格的名称。对于标准阵列,我会这样做:

     let InfoSegueIdentifier = "ToInfoSegue"
    
        override func prepare(for segue: UIStoryboardSegue, sender: Any?)
        {
            if segue.identifier == InfoSegueIdentifier
            {
                let destination = segue.destination as! InfoViewController
                let arrayIndex = tableView.indexPathForSelectedRow?.row
                destination.name = nameArray[arrayIndex!]
              }
        }    
    

    接下来 ViewController ( InfoViewController )

    var name = String()
    
    
        override func viewDidLoad() {
            super.viewDidLoad()
    nameLabel.text = name
        }    
    

    错误:“无法将'[String]'类型的值赋给'String'类型”

    2 回复  |  直到 8 年前
        1
  •  0
  •   Bhavin Kansagara    8 年前

    更改这部分代码

    if segue.identifier == InfoSegueIdentifier
    {
         let destination = segue.destination as! InfoViewController
         let arrayIndex = tableView.indexPathForSelectedRow?.row
         destination.name = nameArray[arrayIndex!]
    }
    

    到

    if segue.identifier == InfoSegueIdentifier
    {
       let destination = segue.destination as! InfoViewController
       let arrayIndexRow = tableView.indexPathForSelectedRow?.row
       let arrayIndexSection = tableView.indexPathForSelectedRow?.section
       destination.name = nameArray[arrayIndexSection!][arrayIndexRow!]
     }
    

    尝试分享结果。

    坠机原因 :在第一个viewController中 [[字符串]] 这是您的部分的数据源。现在,当您试图从这个数组中获取对象时,它将返回 [字符串] 在目标viewController中有 字符串 . 分配时 [字符串]到字符串 它会导致类型不匹配的崩溃。所以,上面的代码所做的是,首先 [字符串] 从 阵列索引部分 然后 字符串 从 阵列索引行 从而将字符串对象传递给目标。

    希望天气转晴。

        2
  •  0
  •   Khushbu    8 年前

    出现此错误是因为您正在将数组传递给第二个视图控制器,并且有一个字符串类型的变量。所以,像这样替换这个方法。

    override func prepare(for segue: UIStoryboardSegue, sender: Any?)
        {
            if segue.identifier == InfoSegueIdentifier
            {
                let destination = segue.destination as! InfoViewController
                if let indexPath = tableView.indexPathForSelectedRow{
                     destination.name = nameArray[indexPath.section][indexPath.row]
                }
    
            }
        }