在这段代码中,我的按钮有一个选中状态和取消选中状态。按下按钮时,它变为绿色,再次按下时变为红色,表示取消选择状态。
但是,所有这些都在 DetailViewController 中,当我从我的 tableView 中选择特定行然后单击按钮以显示绿色并返回并尝试不同的行时,该按钮在另一行上显示绿色,这表示我'我已经按下了(我没有)。我想知道是否有一种方法可以只为我选择的行的 detailView 显示绿色,而为其他行显示红色?
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)
}
}
最佳答案
试试这个-
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)
}
}
关于ios - 如何让每个 tableView 行的 UIButton 状态不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46012447/