7ball
7ball

Reputation: 2315

UISlider value changed not firing

I have a UISlider object in a class like this:

class SliderObject {
  // Other properties
  @IBOutlet weak var slider: UISlider!
  @IBAction func valChange(_ sender: Any) {
    // Not called
  }

  func getView() -> UIView {
    // Return a UIView with the slider in it - the slider is in a nib
    return Bundle.main.loadNibNamed("SliderObjectNib", owner: self, options: nil)?.first as! UIView
  }
}

// In some other View Controller
var s: SliderObject? // <---- This is the solution.. Keep a strong reference to the variable so it won't get released after `viewDidLoad` returns
func viewDidLoad() {
  s = SliderObject()
  self.view.addSubView(s.getView())
}

Everything renders fine. I can see and interact with the slider on my View Controller, but the valChange function never gets called when I scrub the slider... Any thought?

Upvotes: 1

Views: 2013

Answers (2)

Jeni
Jeni

Reputation: 527

You are calling a method from one class to another. This reference is created in a local variable will be released when that method exits. It attempts to call the function on the invalid object. Use delegate - Define a protocol for the method and have your view controller implement that protocol. You can then pass the view controller to the method.

Upvotes: 3

iAviator
iAviator

Reputation: 1447

Add below code:-

// As the slider moves it will continuously call the -valChange:
slider.continuous = true; // false makes it call only once you let go
slider.addTarget(self, action: "valChange:", forControlEvents: .ValueChanged)

Upvotes: 2

Related Questions