swift - 准备使用数组进行 Segue - Xcode 8.0 Swift 3.0

标签 swift xcode segue

将项目添加到一个 VC 上的数组然后使用“准备转场”将数组传输到另一个 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!)

最佳答案

我是 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 将无法找到您尝试修改的变量(标识符),因为它不是当前文件的一部分或导入的一部分。

关于swift - 准备使用数组进行 Segue - Xcode 8.0 Swift 3.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40093716/

相关文章:

Swift Parse 搜索栏不起作用

ios - SwiftUI:拖动逻辑错误或者这是一个错误?

objective-c - UItableviewcell 中的按钮

ios - SwiftyJSON - 'inout JSON' 不可转换为 'JSON'

swift - 使用 iOs 10.0 准备 Segue

ios - swift 从 Appdelegate 转至 UITabBarController

objective-c - 操作系统 X : Saving open application states

ios - 与其他应用程序共享应用程序商店 URL

iphone - 使用 NTimer 更新 NSDateFormatter

ios - 将数组传递给 segue