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?
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.