【问题标题】:Highlighting a button that gets pressed and unhighlighting the non pressed buttons SWIFT突出显示被按下的按钮并取消突出显示未按下的按钮 SWIFT
【发布时间】:2020-08-22 06:03:10
【问题描述】:
我有三个按钮连接到同一个IBAction。他们都有自己的外表。
我发现了如何使按钮在按下时突出显示,而在用户按下另一个按钮时不突出显示。他们是编写代码的更好方法吗?这是我正在使用的:
@IBAction func tipChanged(_ sender: UIButton) {
zeroPCTButton.isSelected = false
tenPCTButton.isSelected = false
twentyPCTButton.isSelected = false
sender.isSelected = true
}
我问的原因是因为我可以制作一个具有一千个按钮的应用程序,并且我不想暴力声明数千次
【问题讨论】:
标签:
ios
swift
uibutton
highlight
【解决方案1】:
我们可以通过以下方式取消突出显示未按下的UIButton,
@IBAction func buttonAction(_ sender: Any) {
let the_tag = (sender as AnyObject).tag;
let button = self.view.viewWithTag(the_tag!) as? UIButton
button?.isSelected = true
button?.backgroundColor = UIColor.white
button?.setTitleColor(UIColor.black, for: .normal)
// Create a list of all tags
let allButtonTags = [1, 2, 3, 4, 5]
let currentButtonTag = (sender as AnyObject).tag
allButtonTags.filter { $0 != currentButtonTag }.forEach { tag in
if let button = self.view.viewWithTag(tag) as? UIButton {
// Deselect/Disable these buttons
button.backgroundColor = #colorLiteral(red: 0.80803, green: 0.803803, blue: 0.805803, alpha: 1)
button.setTitleColor(UIColor.darkGray, for: .normal)
button.isSelected = false
}
}
}
【解决方案2】:
假设您有 1000 个按钮,您需要实现一些循环来执行所有与操作相关的按钮(创建、添加约束、单击事件)。创建 UIButton 数组来存储您的按钮。
var buttons:[UIButton] = []
在创建按钮时将按钮添加到该数组中
for buttonIndex in 1...1000 {
// your other stuff to create, add constraints to button
button.tag = buttonIndex
buttons.append(button)
}
现在您可以轻松实现您的目标。
@IBAction func tipChanged(_ sender: UIButton) {
buttons.forEach({$0.isSelected = $0.tag == sender.tag})
view.layoutIfNeeded()
}