无法使用segue将值从FirstVC传递到SecondVC

时间:2018-03-27 16:28:46

标签: swift macos segue swift4 nsslider

我通过def swap(aList): swap(aList): if len(aList) == 0: return 0 elif len(aList) == 1: print(aList[0]) return aList[0] return aList[0] + swap(aList[2:]) aList = [["abcdefgh"]] swap(aList) segue连接了两个ViewControllers。我需要将Show的值从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
            }
        }
    }
}

enter image description here enter image description here

2 个答案:

答案 0 :(得分:1)

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

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

class SecondViewController: UIViewController {

var imagesQty: Int = 30

...

}

答案 1 :(得分:1)

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

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

然后你可以写

self.performSegue(withIdentifier: .secondVC, sender: slider)

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

发生此错误是因为imagesQtyviewWillAppear而不是在班级的顶级声明。

将其更改为

class SecondViewController: NSViewController {

    var imagesQty = 30 // Int is inferred

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

还有一个错误:prepare(for segue的签名是错误的。一定是

func prepare(for segue: NSStoryboardSegue, sender: Any?) {