我在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
}
错误:"无法将类型'[字符串]'的值分配给类型'字符串'">
更改这部分代码
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!]
}
尝试并分享结果。
崩溃原因:在第一个视图中控制器中,您有 [[字符串]],它是您部分的数据源。现在,当您尝试从此数组中获取对象时,它将返回 [String],并且在目标视图控制器中,您拥有 String 类型的对象。并且在将 [字符串] 分配给字符串时,它会导致类型不匹配的崩溃。因此,上面的代码所做的是,它将首先从arrayIndexSection中获取[String],然后从arrayIndexRow中获取String,从而将String对象传递给目标。
希望它能清除。
您收到此错误是因为您正在将数组传递给第二个视图控制器,并且存在字符串类型的变量。因此,请像这样替换此方法。
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]
}
}
}