问题描述
我希望我的快速代码使用if语句或其他序列,如果每次单击仅在其中一个按钮上显示边框。因此,一次只能在一个按钮上看到边框,而该按钮将是最后一个被按下的按钮。我知道我可以说应该选择每个按钮上带有0的layer.border,但我想看看是否有更有效的方法来做到这一点。
import UIKit
class ViewController: UIViewController {
var ba = UIButton()
var bb = UIButton()
var bc = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
[ba,bb,bc].forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
}
ba.frame = CGRect(x: 0,y: 0,width: 100,height: 100)
bb.frame = CGRect(x: 100,height: 100)
bc.frame = CGRect(x: 200,height: 100)
ba.backgroundColor = .blue
bb.backgroundColor = .orange
bc.backgroundColor = .darkGray
ba.addTarget(self,action: #selector(pressa),for: .touchDown)
bb.addTarget(self,action: #selector(pressb),for: .touchDown)
bc.addTarget(self,action: #selector(pressc),for: .touchDown)
}
@objc func pressa(){
ba.layer.borderWidth = 2
}
@objc func pressb(){
bb.layer.borderWidth = 2
}
@objc func pressc(){
bc.layer.borderWidth = 2
}
}
解决方法
可能是这样的一种方法
[ba,bb,bc].forEach { $0.addTarget(self,action: #selector(pressAll(_:)),for: .touchDown) }
}
@objc func pressAll(_ sender:UIButton) {
[ba,bc].forEach { $0.layer.borderWidth = 0 } // reset all
sender.layer.borderWidth = 2
}
,
您可以在forEach的所有按钮上添加目标,并且只能作为@Sh_Khan提及的一种方法
import UIKit
class ViewController: UIViewController {
var ba = UIButton()
var bb = UIButton()
var bc = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
[ba,bc].forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
$0.addTarget(self,for: .touchDown)
}
ba.frame = CGRect(x: 0,y: 0,width: 100,height: 100)
bb.frame = CGRect(x: 100,height: 100)
bc.frame = CGRect(x: 200,height: 100)
ba.backgroundColor = .blue
bb.backgroundColor = .orange
bc.backgroundColor = .darkGray
}
@objc func pressAll(_ sender:UIButton) {
[ba,bc].forEach { $0.layer.borderWidth = 0 } // reset all
sender.layer.borderWidth = 2
}
}
,
看看您如何在[ba,bc].forEach { ... }
中使用数组来减少代码重复吗?使用数组是关键。与其像这样将三个按钮放在一个数组中内联,不如创建一个属性:
var buttons: [UIButton]!
override func viewDidLoad() {
super.viewDidLoad()
buttons = [ba,bc]
buttons.forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
$0.addTarget(self,action: #selector(buttonPressed),for: .touchDown)
}
...
}
我对所有三个按钮都使用了相同的选择器buttonPressed
。 buttonPressed
可以接受类型为UIButton
的参数,该参数告诉我们按下了哪个按钮:
@objc func buttonPressed(_ sender: UIButton) {
buttons.forEach { ba.layer.borderWidth = 0 } // deselect all buttons first...
sender.layer.borderWidth = 2 // select the tapped button
}
如果要管理3个以上的按钮,建议您完全不要使用UIButton
。您应该使用UICollectionView
。 (Learn how to use them)此视图将为您处理选择。当没有足够的空间显示所有按钮时,它也允许滚动。您只需要创建一个自定义UICollectionViewCell
并覆盖其isSelected
属性:
override var isSelected: Bool {
didSet {
if isSelected {
self.layer.borderWidth = 2
} else {
self.layer.borderWidth = 0
}
}
}