OGeek|极客世界-中国程序员成长平台

标题: ios - 选择一个按钮后,如何取消选择数组中的所有其他按钮? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:50
标题: ios - 选择一个按钮后,如何取消选择数组中的所有其他按钮?

目前,当我在数组中选择一个按钮时,它会从灰色变为黑色,如果再次选择,它会变回灰色,这是我想要的。问题是当我选择一个按钮并选择另一个按钮时,它们都是黑色的。我怎样才能使当我选择一个按钮,然后选择另一个按钮时,前一个按钮会变回灰色?

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)
            }
        }



Best Answer-推荐答案


// 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 { $0.isSelected = false }
}

当你的按钮被选中时,这条线会为你的按钮设置黑色标题颜色..

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

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

关于ios - 选择一个按钮后,如何取消选择数组中的所有其他按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46481673/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4