Search code examples
iosswiftuicontrolmmdrawercontroller

Custom UIControl element with global state for all instances


I have drawer controller presenting menu in the iOS app. This menu is toggled by pressing menu buttons (UIButton) available on each screen.

enter image description here

As you can see in the mock: menu buttons can have red dot showing that new content is available - for this case I simply have two images for menu button without dot and with it.

enter image description here

I thought about making custom UIControl with "global" property for this dot. Is it the right way?

class MenuButton : UIButton {
  static var showNotificationDot : Bool = false
}

Solution

  • For example you could create subclass UIButton and add observer.

    class MyButton: UIButton {
    
        static let notificationKey = NSNotification.Name(rawValue: "MyButtonNotificationKey")
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            self.subcribeForChangingState()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
    
        fileprivate func subcribeForChangingState() {
            NotificationCenter.default.addObserver(forName: MyButton.notificationKey, object: nil, queue: nil) { notificaton in
                if let state = notificaton.object as? Bool {
                    self.changeState(active: state)
                }
            }
        }
    
        fileprivate func changeState(active: Bool) {
            //change ui of all instances
            print(active)
        }
    
        deinit {
            NotificationCenter.default.removeObserver(self)
        }
    }
    

    And change UI from any place like this:

    NotificationCenter.default.post(name: MyButton.notificationKey, object: true)