gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:07:40 24 4
gpt4 key购买 nike

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

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

最佳答案

// 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com