[英]What is the best way to record UISwitch state in UserDefaults in Swift 3
我的(未來)應用程序中有一個設置視圖,帶有4個UISwitch。 我想使用UserDefaults類來記錄開關狀態。
我創建了一個帶有4個屬性(鍵)的結構“SettingsKey”來保存每個開關狀態:
struct SettingsKeys {
static let appShowContactsPhoto = "app.showContactsPhoto"
static let appShowAge = "app.showAge"
static let widgetShowContactsPhoto = "widget.showContactsPhoto"
static let widgetShowAge = "widget.showAge"
}
要加載數據,我在“viewDidLoad”方法中為SettingsKeys中的4個屬性使用4“UserDefaults.standard.bool(forKey:key)”。
保存數據的最佳方法是什么? 我不想在我的視圖控制器中創建4個動作(每個切換一個“valueChanged”動作),所以我只創建了一個。 但是如何使用righ“SettingsKey”屬性映射每個UISwitch? 我想要一個通用代碼(一條指令?),我不希望我的代碼是這樣的:
if sender = switch1 then record data with this key
else if sender = switch2 then record data with this key
else if ...
也許使用UIView標簽?
謝謝。
你可以嘗試這樣的事情
@IBAction func changeSettings(_ sender: UISwitch) {
switch sender.tag {
case 1:
// Change for switch1
break
case 2:
// Change for switch2
break
case 3:
// Change for switch3, etc
break
default:
print("Unknown Switch")
return
}
}
您可以設置標簽( 唯一編號以標識您的視圖/開關 )。
( 在上面的示例中,它們分別為1,23)用於每個開關。
我使用了Wolverine提出的UIView.tag屬性:
然后我修改了我的結構:
struct SettingsKeys {
// Application Settings
static let appShowContactsPhoto = "app.showContactsPhoto"
static let appShowAge = "app.showAge"
// Widget Settings
static let widgetShowContactsPhoto = "widget.showContactsPhoto"
static let widgetShowAge = "widget.showAge"
// All settings
static let serialized = [
0: appShowContactsPhoto,
1: appShowAge,
10: widgetShowContactsPhoto,
11: widgetShowAge,
]
}
我的行動:
// Click on a switch button
@IBAction func changeSetting(_ sender: UISwitch) {
UserDefaults.standard.set(sender.isOn, SettingsKeys.serialized[sender.tag]!)
}
它工作正常!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.