作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有 swift 中复选框的工作代码,但我想要构建的项目有大约 50 个左右的复选框。为了与更少的代码是最好的目标保持一致,我想知道是否有更好的方法来将其全部写出来,而不仅仅是复制和粘贴。我尝试将多个按钮链接到一个 iboutlet,但我想这不是查看不同按钮如何注册选择然后点击的按钮的方法。
工作代码:
@IBOutlet weak var buttonOne: UIButton!
var isButtonClicked: Bool!
override func viewDidLoad() {
super.viewDidLoad()
isButtonClicked = false
}
@IBAction func buttonClicked(_ sender: UIButton) {
if isButtonClicked == true {
isButtonClicked = false
}
else {
isButtonClicked = true
}
if isButtonClicked == true {
buttonOne.setImage(#imageLiteral(resourceName: "ButtonClicked"), for: .normal)
}
else {
buttonOne.setImage(#imageLiteral(resourceName: "ButtonUnclicked"), for: .normal)
}
}
最佳答案
我建议您为复选框创建一个类。示例:
class CheckBox: UIButton {
var checked = false {
didSet {
if checked == true {
self.setImage(#imageLiteral(resourceName: "ButtonClicked"), for: .normal)
}
else {
self.setImage(#imageLiteral(resourceName: "ButtonUnclicked"), for: .normal)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.addTarget(self, action: #selector(tapped), for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func tapped() {
self.checked = !self.checked
if checked == true {
self.setImage(#imageLiteral(resourceName: "ButtonClicked"), for: .normal)
}
else {
self.setImage(#imageLiteral(resourceName: "ButtonUnclicked"), for: .normal)
}
}
}
然后,您可以使用此类通过 for 循环以编程方式创建复选框。示例:
for i in 0..<50 {
let checkbox = CheckBox(frame: CGRect(x: 0, y: i * 40, width: 40, height: 40))
checkbox.tag = 1
self.someView.addSubview(checkbox)
}
关于swift - swift 3 中的多个复选框按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41996396/
我是一名优秀的程序员,十分优秀!