【问题标题】:How to pass value from 2d array with prepareForSegue如何使用 prepareForSegue 从二维数组传递值
【发布时间】:2018-08-08 06:14:10
【问题描述】:

我在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'”

【问题讨论】:

  • 你想在 nameLabel.text 中存储什么?
  • 你定义的'array'是数组里面的字符串数组,所以这个错误肯定会出现。

标签: arrays swift uitableview segue


【解决方案1】:

修改这部分代码

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 中,您有 [[String]],这是您的部分的数据源。现在,当您尝试从该数组中获取对象时,它会返回 [String] 并且在您的目标 viewController 中您拥有 String 类型的对象。并且在将 [String] 分配给 String 时,它会导致类型不匹配的崩溃。所以,上面代码的作用是,首先从 arrayIndexSection 获取 [String],然后从 arrayIndexRow 获取 String strong> 并因此将 String 对象传递到目的地。

希望它清除。

【讨论】:

    【解决方案2】:

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

    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]
                }
    
            }
        }  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 2013-02-19
      • 2020-03-02
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多