我试图通过保存状态来完成我最喜欢的按钮,即使我退出了视图\ App。如果有人能告诉我我该怎么做,那将是很棒的,我使用Xcode 8并使用Swift 3进行编码。
//create a new button
let Favoritebutton: UIButton = UIButton(type: UIButtonType.custom)
//set image for button
Favoritebutton.setImage(UIImage(named: "EmptyHeart.png"), for: .normal)
Favoritebutton.setImage(UIImage(named: "FilledHeart.png"), for: .selected)
//add function for button
Favoritebutton.addTarget(self, action: #selector(self.button), for: .touchUpInside)
//set frame
Favoritebutton.frame = CGRect(x:0,y: 0,width: 35,height: 35)
let barButton = UIBarButtonItem(customView: Favoritebutton)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barButton
let state = UserDefaults.standard.bool(forKey: "isSaved") ?? false
}
@IBAction func button(sender: UIButton) {
sender.isSelected = !sender.isSelected
UserDefaults.standard.set(true,forKey: "isSaved")
UserDefaults.standard.synchronize()
if let Favoritebutton = sender as? UIButton {
if Favoritebutton.isSelected {
// set selected
Favoritebutton.isSelected = true
UserDefaults.standard.set(true, forKey: "MY_FAV_KEY")
UserDefaults.standard.synchronize()
// set badge to tabbar item.
let tabItem = self.tabBarController?.tabBar.items![3]
sel_val = tabItem?.badgeValue
if(sel_val == nil){
sel_val = "0"
}
let sel_num = Int(sel_val!)
tabItem!.badgeValue = String(format: "%d", sel_num! + 1) as String
let Fav: NSMutableArray = []
Fav.add(barImage)
Fav.add(barName)
Fav.add(streetName)
favorite.add(Fav)
} else {
// set deselected
Favoritebutton.isSelected = false
UserDefaults.standard.set(true, forKey: "MY_FAV_KEY")
UserDefaults.standard.synchronize()
let tabItem = self.tabBarController?.tabBar.items![3]
sel_val = tabItem?.badgeValue
if(sel_val == nil){
sel_val = "0"
}
let sel_num = Int(sel_val!)
tabItem!.badgeValue = String(format: "%d", sel_num! - 1) as String
let Fav: NSMutableArray = []
Fav.add(barImage)
Fav.add(barName)
Fav.add(streetName)
favorite.remove(Fav)
}
}
正如我所说,如果有人能帮助我保存按钮状态,那将会很棒 即使我退出了视图或应用程序,我也会非常感激,提前谢谢!
答案 0 :(得分:1)
将值保存到UserDefaults会将其写入plist文件。应用程序恢复时,它不会读回值或恢复状态。你对此负责。所以viewDidLoad中的某个地方检查状态:
let state = UserDefaults.standard.bool(forKey: "isSaved") ?? false
然后相应地设置按钮