选择一个按钮后,如何取消选择阵列中的所有其他按钮?

How can I deselect all other buttons in array when one is selected?

目前,当我 select 数组中的一个按钮时,它会从灰色变为黑色,如果再次 selected,它会变回灰色,这是我想要的。问题是当我 select 一个按钮和 select 另一个按钮时,它们都将是黑色的。当我 select 一个按钮,然后 select 另一个按钮时,我怎样才能做到这一点,前一个按钮会变回灰色?

let subjectArray = ["Button1", "Button2", "Button3", "Button4"]   
for title in subjectArrary {
                let button = UIButton()
                button.backgroundColor = UIColor.white
                button.setTitle("\(title)", for: .normal)
                button.setTitleColor(UIColor.gray, for: .normal)
                button.heightAnchor.constraint(equalToConstant: 60).isActive = true
                button.widthAnchor.constraint(equalToConstant: 140).isActive = true
                button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)

                stack.addArrangedSubview(button)
            }



    func buttonPressed(sender:AnyObject) {

            guard let button = sender as? UIButton else { return }

            if !button.isSelected {
                button.isSelected = true
                button.setTitleColor(UIColor.black, for: .normal)
            } else {
                button.isSelected = false
                button.setTitleColor(UIColor.gray, for: .normal)
            }
        }

使用NotificationCenter.

  1. 定义自定义通知名称。
  2. 使用以下方法订阅所有按钮以收听通知:NotificationCenter.default.addObserver(...
  3. 在您的按钮 控制操作 方法中 class,post 带有 object 的通知(即通知的发送者) 设置为 self.
  4. 在通知注册的通知处理程序方法中,检查通知的object属性。如果等于self,取消选中当前按钮

如果您有奥特莱斯系列:

@IBOutlet var buttons: [UIButton]!

您可以检测到哪个被选中了

func buttonPressed(sender:AnyObject) {

        guard let currentButton = sender as? UIButton else { return }

        buttons.forEach{ (element) in
                if element == currentButton {
                      //change state and params for current button
                }else{
                     //change other buttons
                }
        }
    }

当您创建按钮时,您可以将它们添加到数组中,例如

let bs = [UIButton]()    
for title in subjectArrary {
    let b = .......
    bs.append(b)
}

并在动作方法中

for b in bs {
    b.setTitleColor(.gray, for: .normal)
}
(sender as? UIButton).setTitleColor(.black, for: .normal)

尝试创建一个按钮数组

var buttonArray = [UIButton]()


func buttonPressed(sender:AnyObject) {
    let _ = buttonArray.map({[=10=].isSelected = false})
    sender.isSelected = true
}

这样就可以了

如果你想在按下新按钮时重置其他按钮的状态,那么你可以使用以下代码,

/**
 Reset the default state of the buttons
 */
func resetButtonStates() {
    for button in [YOUR_BUTTON_ARRAY_VARIABLE_HERE] {
        button.isSelected = false
        button.setTitleColor(UIColor.gray, for: .normal)
    }
}

func buttonPressed(sender:AnyObject) {
    guard let button = sender as? UIButton else { return }

    // Check wether the button is selected already, to be used as mentioned below
    let isAlreadySelected = sender.isSelected == true

    // Reset the default state to all the buttons
    resetButtonStates()

    // Now update the button state of the selected button alone if its not selected already
    if !isAlreadySelected {
        button.isSelected = true
        button.setTitleColor(UIColor.black, for: .normal)
    } else {
        // Do Nothing since as per your case if you selected the already selected button it should change to disable right, so the resetButtonStates() will do that.
    }
}
// Create an array of buttons which will hold all of your buttons
// This is a class property, we can already initialise this with empty array so we don't need to set it during class init()
let buttons: [UIButton] = [] 

func createButton(withTitle title: String) -> UIButton {
    let button = UIButton()
    button.setTitle(title, for: .normal)
    button.setTitleColor(.gray, for: .normal)
    button.setTitleColor(.black, for: .selected) // Please take note I've added this line
    button.backgroundColor = .white
    button.widthAnchor.constraint(equalToConstant: 140).isActive = true
    button.heightAnchor.constraint(equalToConstant: 60).isActive = true
    button.addTarget(self, action: #selector(didTapButton(_:)), for: .touchUpInside)
    return button
}

func setupButtons() {
    let subjectArray = ["Button1", "Button2", "Button3", "Button4"]   

    for title in subjectArrary {
        let button = createButton(withTitle: title)
        buttons.append(button) // Append all your buttons
        stack.addArrangedSubview(button)
    }
}

func didTapButton(_ button: UIButton) {
    deselectAllButtons()
    button.isSelected = !button.isSelected // set/unset of button state happens here
}

func deselectAllButtons() {
    buttons.forEach { [=10=].isSelected = false }
}

选中此行后,将为您的按钮设置黑色标题颜色..

button.setTitleColor(.black, for: .selected)

为了获得更简洁的代码,我提取了您的 for 循环中的代码,制作了一小块方法.. 另外,无需将我的代码注释添加到您的实际代码中;)