如何让每个 tableView 行的 UIButton 状态不同? [英] How can I get the UIButton state to be different for each tableView row?

查看:49
本文介绍了如何让每个 tableView 行的 UIButton 状态不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中,我的按钮有一个选择状态和一个取消选择状态.当按钮被按下时,它变为绿色,再次按下时它变为红色以表示取消选择状态.

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.

但是,所有这些都在 DetailViewController 中,当我从 tableView 中选择特定行然后单击按钮显示绿色并返回并尝试不同的行时,按钮在另一行上显示绿色,这表示我已经按下它(我没有).我想知道是否有办法只为我选择的行的 detailView 显示绿色而为其他行显示红色?

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)

}
}

推荐答案

试试这个 -

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)

    }
}

这篇关于如何让每个 tableView 行的 UIButton 状态不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆