macosswift4nsviewnsslider

How to update NSImageView using NSSlider?


I have an NSSlider in FirstViewController. I have 12 NSImageViews in SecondViewController. I'd like to move a slider in first window and shuffle images in these 12 views in second window.

How to update these NSImageViews every time when moving the slider?

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 
        }
    }
}

Solution

  • First of all be aware that any move of the slider performs a new segue. To avoid that declare a boolean property which is set when the segue is performed the first time and could be reset after the second view controller has been dismissed.

    To update the value in the second view controller keep the reference and call a method

    Actually with this code you don't need the slider 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)
       }
    

    Honestly I would use a button to perform the segue and move the slider into the second view controller. To shuffle the array use an Array extension and as view an NSCollectionView rather than a bunch of image views