Search code examples
iosswiftkey-value-observinguipagecontrol

Can't observe UIPageControl's currentPage changes in Swift


I've a subclass of UIPageControl, and I'd like to observe the changes in currentPage.

Unfortunately, my currentPage's didSet isn't called when currentPage changes from taps on MyPageControl.

class MyPageControl: UIPageControl {
    override var currentPage: Int {
        didSet {
            // not called when `currentPage` is changed from a tap
            updateSomething(for: currentPage)
        }
    }
}

And the change can't be observed using KVO either:

class MyPageControl: UIPageControl {
    var observation: NSKeyValueObservation?
    override func awakeFromNib() {
        super.awakeFromNib()
        observation = observe(\.currentPage) { (_, _) in
            // not called when `currentPage` is changed from a tap
            updateSomething(for: self.currentPage)
        }
    }
}

Solution

  • You may detect the taps with sendAction(_:to:for:) and read the value of currentPage at that moment.

    class MyPageControl: UIPageControl {
        override func sendAction(_ action: Selector, to target: Any?, for event: UIEvent?) {
            super.sendAction(action, to: target, for: event)
            updateSomething(for: currentPage)
        }
    }