按下两个 UIButton 时如何更改它们的颜色?



我正在尝试使用两个按钮在动画滑动视图之间切换。当 UIView 加载时,我希望 button1 是 UIColor.darkGrey,按钮 2 是 UIColor.lightGrey。然后,当我按下按钮2时,我希望按钮2变成UIColor.darkGrey,按钮1变成UIColor.lightGrey。如果我按下按钮 1,我希望按钮 1 是 UIColor.darkGrey,按钮 2 是 UIColor.lightGrey。

这似乎很简单;使用故事板,我连接了一个用于按钮 1 和按钮 2 的 UIButton 作为出口。然后我把每个都连接起来作为动作。在每个操作中,我都包含以下代码:

@IBAction func button1Action(_ sender: UIButton) {
button2.titleLabel?.textColor = UIColor.lightGray
button1.titleLabel?.textColor = UIColor.darkGray
UIView.animate(withDuration: 1){
self.side1.constant = 0
self.side2.constant = 0
self.sideA.constant = 400
self.sideB.constant = -400
self.view.layoutIfNeeded()
}
}
@IBAction func button2Action(_ sender: UIButton) {
button1.titleLabel?.textColor = UIColor.lightGray
button2.titleLabel?.textColor = UIColor.darkGray
view.layoutIfNeeded()
UIView.animate(withDuration: 1){
self.side1.constant = -400
self.side2.constant = 400
self.sideA.constant = 0
self.sideB.constant = 0
self.view.layoutIfNeeded()
}

}

当我按下按钮 1 时,一切都按预期工作;但是,每当我按下按钮2时,两个按钮都是UIColor.lightGrey。我错过了一些明显的东西吗?

您可以"免费"获得一些带有按钮的方法来管理其状态。其中之一是isSelected.另一个是tag属性,因此您可以确定哪个按钮是哪个按钮。由于您只有两个按钮,因此您只需使用isSelected即可确定哪个是哪个。您还可以使用计算vars来使您的生活更轻松。考虑到这些事项,您可以使用以下一种方法来管理按钮的状态:

  1. 声明一个buttons计算的变量,如下所示

    @IBOutlet var firstButton: UIButton!
    @IBOutlet var secondButton: UIButton!
    // computed var to access your buttons
    private var buttons: [UIButton] {
    return [firstButton, secondButton]
    }
    
  2. viewDidLoad中设置按钮。

    override func viewDidLoad() {
    super.viewDidLoad()
    // one setup to configure each button for selected or not selected
    buttons.forEach { button in
    button.setTitleColor(.darkGray,
    for: .selected)
    button.setTitleColor(.lightGray,
    for: .normal)
    }
    firstButton.isSelected = true
    }
    

func setTitleColor(_ color: UIColor?, for state: UIControl.State)将在按钮的生存期内保持有效,因此在初始声明后无需摆弄它(除非您以后要更改按钮的行为(。

    两个
  1. 按钮@IBAction一个,并利用tag属性来确定哪个是哪个。由于您只有两个按钮,因此我只使用isSelected.以下是您的单个@IBAction的外观:

    @IBAction func buttonAction(_ sender: UIButton) {
    UIView.animate(withDuration: 1.0) {
    // flip buttons
    self.buttons.forEach { button in
    button.isSelected.toggle()
    }
    if self.firstButton.isSelected {
    // tweak your constraints for firstButton.isSelected == true
    // tweak your constraints for secondButton.isSelected == false
    } else {
    // tweak your constraints for firstButton.isSelected == false
    // tweak your constraints for secondButton.isSelected == true
    }
    }
    }
    

根据您当前的实现,您需要右键单击情节提要上的UIButtons并破坏现有的IBAction连接,然后将两个按钮重新连接到上述方法。

最新更新