0

我有两个ViewControllers通过Showsegue 连接。我需要将NSSlider' 值从ViewControllerto 传递给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)
    }
}

在此处输入图像描述 在此处输入图像描述

4

2 回答 2

1

您无法更改该值,因为 var 是在函数中定义的,而不是在类中定义的。

使您的 var 成为类属性,它应该可以工作。

class SecondViewController: UIViewController {

var imagesQty: Int = 30

...

}
于 2018-03-27T16:34:34.843 回答
1

首先,目的和好处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?) {
于 2018-03-27T16:37:44.073 回答