我已经在整个项目中都使用了一个uibutton。这些UIBUTTON子类将具有边框颜色,该边框颜色会根据用户在设置中选择的内容进行更改。使用UserDefaults保存设置。
问题:当我第一次加载应用程序时,按钮边框是正确的颜色 - 但是,当我更改设置时(最终更改按钮边框( - 什么也不会发生。当我关闭应用程序并重新打开时,按钮只会更改颜色。
我的代码
class CustomSeasonButton: UIButton {
var seasonCold = Bool()
let nsDefaults = UserDefaults.standard
var notification = Notification(name: Notification.Name(rawValue: "themeChanged"))
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// ...
self.seasonCold = nsDefaults.bool(forKey: "savedSeasonDefault")
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshButtonBorder), name: notification.name, object: nil)
refreshButtonBorder()
}
func refreshButtonBorder() {
print("Notification Received")
if seasonCold {
seasonCold = false
self.layer.borderColor = UIColor.blue
}
else {
seasonCold = true
self.layer.borderColor = UIColor.red
}
}
}
设置
class SettingsVC: UITableViewController {
//...
var notification = Notification(name: Notification.Name(rawValue: "themeChanged"))
//...
}
,然后在季节的基础上选择 - 我有以下内容:
NotificationCenter.default.post(notification)
因此,正如您从上面的代码中看到的那样,按钮边框颜色应该在蓝色和红色之间切换,具体取决于用户defaults选择的内容。
我可以更改边框颜色的唯一方法是关闭应用程序并重新打开应用。
问题:如何确保UIBUTTON子类每次更新设置(用户默认未违反(时都会更改边框颜色?谢谢!
seasonCold = false {
didSet {
refreshButtonBorder()
}
}
func refreshButtonBorder() {
if seasonCold {
self.layer.borderColor = UIColor.blue
}
else {
self.layer.borderColor = UIColor.red
}
}
并在更改UserDefaults" SavedSeasonDefault"
时设置SELINECOLD对于一对多呼叫,使用通知中心,子分类按钮的每个实例都应具有通知observer,并且每当UserDefaults更改
时发布通知var notification = Notification(name: Notification.Name(rawValue: "seasonChanged"))
在NIB或您的Init功能的醒着中
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshButtonBorder), name: notification.name, object: nil)
每当季节变化时,撒些通知灰尘
NotificationCenter.default.post(notification)
供您的按钮随时更改,他们必须知道设置已更改。他们将不得不收听某种广播消息,并在修改设置时采取一些措施。一种方法可能是通过NSnotificationCenter-创建时的所有按钮都可以在默认通知中心收听消息,然后在您注意到设置已更改时,您可以广播消息。
至于上面的代码,请注意,您将在init
方法中设置边框颜色。当创建按钮时,该方法完全调用一次。这就解释了为什么您的按钮的边框颜色不会改变...创建时的颜色是建立的。
最后,您(如果您不知道(了解有关[UIAppearance][1]
及其允许您立即影响整个控件组的颜色和样式的更多信息可能感兴趣的。