【问题标题】:iOS UIButtons - Toggle backgrounds when 1 is selected, others are notiOS UIButtons - 选择 1 时切换背景,其他则不
【发布时间】:2020-12-10 19:57:50
【问题描述】:

我有多个按钮,代表数据输入(分数)。选择1个按钮时,将其后台更改为1颜色。所有其他按钮都应设置为不同的颜色,以显示当前选择(切换)的颜色。

我已使用来自此thread 的信息来实现@IBAction 函数来更改按钮。我以 Swift v4 回复/解决方案为基础,本质上是一个单一的功能:

    @IBAction func buttonPressToggle(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        if sender.isSelected {
            sender.backgroundColor = UIColor.orange
        } else {
            sender.backgroundColor = UIColor.green
        }
    }

所有按钮都使用相同的功能,所以我可以通过sender 局部变量来定位按钮。我也可以使用tag 属性,但我目前还没有做任何事情。

缺少的是“重置”任何其他按钮的状态/背景颜色,因为它不再被选中。

【问题讨论】:

    标签: ios swift xcode uibutton


    【解决方案1】:
        @IBAction func buttonPressToggle(_ sender: UIButton) {
            self.buttons.forEach {
                $0.backgroundColor = ($0 == sender) ? UIColor.orange : UIColor.green
            }
        }
    

    【讨论】:

    • 伟大而简单的解决方案。会试试看。
    【解决方案2】:

    您可以执行以下操作:

    class ViewController: UIViewController {
    
        @IBOutlet var collectionOfButtons: Array<UIButton>?
        
        private let selectionColor = UIColor.orange
        private let nonSelectedColor = UIColor.green
        
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
        }
    
        @IBAction func buttonPressToggle(_ sender: UIButton) {
            guard let buttons = collectionOfButtons else { return }
            
            for btn in buttons {
                if btn.tag == sender.tag {
                    btn.backgroundColor = selectionColor
                } else {
                    btn.backgroundColor = nonSelectedColor
                }
            }
        }
    

    所以基本上我们将每个按钮的出口存储在一个数组中,如果一个按钮被选中,我们循环遍历这个数组并检查当前按钮 (btn) 是否是选中的,如果是,我们将其设置为backgroundColor 到另一个。
    因此,对于这种方法,应标记按钮。

    我已经上传了我的示例项目:https://github.com/finebel/ToggleButtons

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-21
      • 2011-11-18
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多