我有两个ViewControllers通过Showsegue连接。我需要把NSSlider的值从ViewController传递到SecondViewCotroller
因此,在ViewController中移动滑块,变量将在SecondViewController中更新。
如何更新imagesQty变量的值?

// FIRST VIEW CONTROLLER

import Cocoa

class ViewController: NSViewController {

    @IBOutlet weak var slider: NSSlider!
    @IBOutlet weak var photosLabel: NSTextField!

    @IBAction func segueData(_ sender: NSSlider) {
        photosLabel.stringValue = String(slider.intValue) + " photos"
        self.performSegue(withIdentifier: NSStoryboardSegue.Identifier(rawValue: "SegueIdentifierForSecondVC"), sender: slider)
    }

    func prepare(for segue: NSStoryboardSegue, sender: NSSlider?) {
        if segue.identifier!.rawValue == "SegueIdentifierForSecondVC" {
            if let secondViewController =
            segue.destinationController as? SecondViewController {
                secondViewController.imagesQty = slider.integerValue
            }
        }
    }
}


// SECOND VIEW CONTROLLER

import Cocoa

class SecondViewController: NSViewController {

    var imagesQty = 30

    override func viewWillAppear() {

    super.viewWillAppear()
    self.view.wantsLayer = true

    print("viewWillAppear – Qty:\(imagesQty)")

    //let arrayOfViews: [NSImageView] = [view01...view12]

    let url = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Desktop/ArrayOfElements")
    do {
        let fileURLs = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]).reversed()
        let photos = fileURLs.filter { $0.pathExtension == "jpg" }

        for view in arrayOfViews {
            //"imagesQty" is here
            let i = Int(arc4random_uniform(UInt32(imagesQty-1)))
            let image = NSImage(data: try Data(contentsOf: photos[i]))
            view.image = image
            view.imageScaling = .scaleNone
        }
    } catch {
        print(error)
    }
}

swift - 无法使用segue将值从FirstVC传递给SecondVC-LMLPHP
swift - 无法使用segue将值从FirstVC传递给SecondVC-LMLPHP

最佳答案

首先,NSStoryboardSegue.Identifier的目的和好处是创建一个能够避免文本的扩展。

extension NSStoryboardSegue.Identifier {
    static let secondVC = NSStoryboardSegue.Identifier("SegueIdentifierForSecondVC")
}

那你就可以写了
self.performSegue(withIdentifier: .secondVC, sender: slider)


if segue.identifier! == .secondVC { ...

发生此错误的原因是imagesQty是在viewWillAppear中声明的,而不是在类的顶层声明的。
把它改成
class SecondViewController: NSViewController {

    var imagesQty = 30 // Int is inferred

    // override func viewWillAppear() {
    //     super.viewWillAppear()
    // }
}

还有一个错误:prepare(for segue的签名是错误的。一定是
func prepare(for segue: NSStoryboardSegue, sender: Any?) {

09-27 10:29