How can I get the UIButton state to be different for each tableView row?

微笑、不失礼 提交于 2019-12-24 08:03:56

问题


In this code I have a selected state and deselected state for my button. When the button has been pressed, it changes to green and when pressed again it changes to red to represent a deselected state.

However, all this is in a DetailViewController and when I select a particular row from my tableView then click the button to show green and go back and try a different row, the button shows green on this other row which signifies that I've pressed it(I haven't). I was wondering if there was a way to only show green for detailView of the row I selected and red for the others?

 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)

}
}

回答1:


Try this -

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)

    }
}


来源:https://stackoverflow.com/questions/46012447/how-can-i-get-the-uibutton-state-to-be-different-for-each-tableview-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!