在一个VC上将项添加到数组然后使用"准备segue"的最佳方法是什么?将阵列转移到另一个VC?到目前为止,这是我设法提出的:(VC1)
var items: [String] = ["Hello"]
(VC2):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var destViewController: ViewController = segue.destination as! ViewController
destViewController.items = [textField.text!]
items.append(textField.text!)
}
在VC2上出现一个错误,指出"使用未解析的标识符"在线
items.append(textField.text!)
答案 0 :(得分:4)
我是iOS / Swift的新手,但我最近遇到了同样的情况。我就是这样做的。
SourceViewController.swift
class SourceViewController: UIViewController {
let stringToPass = "Hello World"
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! DestinationViewController
destinationVC.receivedString = stringToPass
}
}
DestinationViewController.swift
class DestinationViewController: UIViewController {
var receivedString: String?
if let newString = receivedString {
print(newString)
}
...
我意识到这与您的示例略有不同,但需要注意的重要一点是,当您创建“destinationVC”时,您可以修改它的属性。关键的区别是你必须在赋值时提供变量(destinationVC.receivedString)的范围,或者在你的情况下附加到数组:
destViewController.items.append(textField.text!)
在没有提供范围的情况下,Xcode无法找到您尝试修改的变量(标识符),因为它不是当前文件的一部分或导入的一部分。
答案 1 :(得分:0)
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print("thank you very much for your helpful suggestions")
print("I think I am pointed at the right direction")
print("Thanks again for your generous contributions")
print("Apoligies! Stackoverflow is pretty well automated to allow me to put it in non programatic format")
}

答案 2 :(得分:0)
在您使用UITableView的情况下,我会在我的项目中使用以下代码:
// On first viewController
public override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue" {
let vc = segue.destination as! VC2
vc.data = sender as! [String]
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
var dataArray: [String] = []
dataArray.append(items[indexPath.row].id)
dataArray.append(items[indexPath.row].title)
dataArray.append( items[indexPath.row].details)
performSegue(withIdentifier: "segue", sender: dataArray)
}
只需紧紧抓住您的阵列
var data: [String] = []
id.text = data[0]
title.text = data[1]
details.text = data[2]