我有两个ViewControllers
通过Show
segue连接。我需要把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)
}
}
最佳答案
首先,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?) {