我已經在我的項目中使用了UIButton的子類。這些UIButton子類將具有根據用戶在設置中選擇的內容而改變的邊框顏色。該設置用UserDefaults保存。通過UserDefault設置更新子類UIButton的屬性
問題: 當我加載的應用程序的第一次,按鈕邊框是正確的顏色 - 但是,當我改變設置(以最終改變按鈕邊框) - 什麼也沒有發生。一旦我關閉了應用並重新打開,按鈕只會改變顏色。
我的代碼
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"))
//...
}
然後在賽季IBAction爲選擇 - 我有以下幾點:
NotificationCenter.default.post(notification)
因此,您可能會從上面的代碼中看到,按鈕邊框顏色應該在藍色和紅色之間切換,具體取決於UserDefaults選擇的內容。
我可以改變邊框顏色的唯一方法就是關閉應用程序並重新打開它。
問題: 我怎樣才能確保UIButton的子類得到了邊框顏色更改每次設置(UserDefaults)更新時間?謝謝!
你想改變現有的按鈕設置改變時? – rmaddy
@rmaddy - 正確!用戶可以在設置視圖中更改季節設置。根據選擇哪個季節,其他(子類)UIButton的邊框顏色應相應更改。 – Joe