自定义UIControl元素,具有所有实例的全局状态

时间:2018-04-28 07:41:18

标签: ios swift uicontrol mmdrawercontroller

我在iOS应用程序中有抽屉控制器显示菜单。 通过按每个屏幕上可用的菜单按钮(UIButton)来切换此菜单。

enter image description here

正如你在模拟中看到的那样:菜单按钮可以有红点显示新内容可用 - 对于这种情况,我只有两个图像用于菜单按钮,没有点和它。

enter image description here

我考虑过为这个点制作具有“全局”属性的自定义UIControl。这是正确的方式吗?

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

1 个答案:

答案 0 :(得分:1)

例如,您可以创建子类UIButton并添加观察者。

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

从以下任何地方更改用户界面:

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