如何使用NSSlider更新NSImageView?

时间:2018-03-28 00:40:08

标签: macos swift4 nsview nsslider

我在NSSlider中有一个FirstViewController。我在NSImageViews中有12 SecondViewController。我想在第一个窗口中移动一个滑块,并在第二个窗口中的这12个视图中随机播放图像。

每次移动滑块时如何更新这些NSImageViews

SecondViewController

var imagesQty = 100  

override func viewWillAppear() {

    super.viewWillAppear()

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

    for view in arrayOfViews {
        let i = Int(arc4random_uniform(UInt32(imagesQty-1)))
        let image = NSImage(data: try Data(contentsOf: photos[i]))
        view.image = image
    }
}

的ViewController

@IBOutlet weak var slider: NSSlider!

@IBAction func segueData(_ sender: NSSlider) {
    self.performSegue(withIdentifier: .secondVC, sender: slider)
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
    if segue.identifier! == .secondVC {
        if let secondViewController =
            segue.destinationController as? SecondViewController {
            secondViewController?.imagesQty = slider.integerValue 
        }
    }
}

1 个答案:

答案 0 :(得分:1)

首先要知道滑块的任何移动都会执行新的segue。为了避免这种情况,声明了第一次执行segue时设置的布尔属性,并且可以在第二个视图控制器被解除后重置。

要更新第二个视图控制器中的值,请保留引用并调用方法

实际上,使用此代码,您不需要滑块IBOutlet

class ViewController: NSViewController {


    var secondControllerIsPresented = false
    var secondController : SecondViewController?

...


    @IBAction func segueData(_ sender: NSSlider) {

        if !secondControllerIsPresented {
            self.performSegue(withIdentifier: .secondVC, sender: sender)
            secondControllerIsPresented = true
        } else {
            secondController?.updateArray(value: sender.integerValue)
        }
    }

    override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
        if let identifier = segue.identifier, identifier == .secondVC {
            let secondViewController = segue.destinationController as! SecondViewController
            secondController = secondViewController
            let slider = sender as! NSSlider
            secondViewController.imagesQty = slider.integerValue
        }
    }

...
class SecondViewController: NSViewController {

...


   func updateArray(value : Int) {
       print(value)
   }

老实说,我会使用一个按钮来执行segue并将滑块移动到第二个视图控制器中。要对数组进行随机播放,请使用Array扩展名并查看NSCollectionView而不是一堆图片视图