UISlider 值更改未触发

UISlider value changed not firing

我在 class 中有一个 UISlider 对象,如下所示:

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

一切都很好。我可以在我的 View Controller 上看到滑块并与之交互,但是当我滑动滑块时 valChange 函数永远不会被调用...有什么想法吗?

添加以下代码:-

// 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)

您正在从一个 class 调用一个方法到另一个。此引用在局部变量中创建,将在该方法退出时释放。它尝试调用无效对象上的函数。 使用委托 - 为该方法定义一个协议,并让您的视图控制器实现该协议。然后您可以将视图控制器传递给该方法。