在这段代码中,我有一个选中的状态和取消选择的按钮状态。按下按钮时,它会变为绿色,再次按下时,它会变为红色以表示取消选择的状态。
但是,所有这些都在DetailViewController中,当我从tableView中选择一个特定的行,然后单击按钮显示绿色并返回并尝试不同的行,该按钮在另一行显示绿色表示我'我按下了它(我没有)。我想知道是否有一种方法只显示我选择的行的详细信息绿色和其他的红色?
let defaults = UserDefaults.standard
// Outlets
@IBOutlet weak var goingButton: UIButton!
// Actions
@IBAction func goingButtonTapped(_ sender: UIButton) {
goingButton.isSelected = !goingButton.isSelected
if goingButton.isSelected == true {
goingButton.setImage(UIImage(named: "goingSelected"), for: UIControlState.selected)
defaults.set(true, forKey: "going")
defaults.synchronize()
defaults.bool(forKey: "going")
print("defaults: \(defaults)")
} else if goingButton.isSelected == false {
goingButton.setImage(UIImage(named: "goingDeselected"), for: UIControlState.normal)
defaults.set(false, forKey: "going")
defaults.synchronize()
defaults.bool(forKey: "going")
}
}
override func viewDidLoad() {
super.viewDidLoad()
goingButton.setImage(UIImage(named: "goingDeselected"), for: UIControlState.normal)
if defaults.bool(forKey: "going")
{
goingButton.isSelected = true
goingButton.setImage(UIImage(named: "goingSelected"), for: UIControlState.selected)
}
}
答案 0 :(得分:1)
试试这个 -
override func viewDidLoad() {
super.viewDidLoad()
goingButton.setImage(UIImage(named: "goingDeselected"), for: UIControlState.normal)
if defaults.bool(forKey: "going")
{
goingButton.isSelected = true
goingButton.setImage(UIImage(named: "goingSelected"), for: UIControlState.selected)
}
}