Swift 4中的UIButton数组 [英] Array of UIButtons in Swift 4
问题描述
我在UiKit中使用UIButtons制作了一系列复选框:
I've made a series of checkboxes in UiKit with UIButtons:
@IBOutlet weak var Box1: UIButton!
@IBOutlet weak var Box2: UIButton!
@IBOutlet weak var Box3: UIButton!
....
@IBOutlet weak var Box59: UIButton!
// Gives the button an action
@IBAction func Box1(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
}
@IBAction func Box2(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
}
@IBAction func Box3(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
}
....
@IBAction func Box59(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
}
// Creates button images of checkbox and unchecked box
var BoxON = UIImage(named: "CheckBox")
var BoxOFF = UIImage(named:"UnCheckBox")
// Allows the button to be set to the image, if selected or not
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Box1.setImage(BoxOFF, for: .normal)
Box1.setImage(BoxON, for: .selected)
Box2.setImage(BoxOFF, for: .normal)
Box2.setImage(BoxON, for: .selected)
Box3.setImage(BoxOFF, for: .normal)
Box3.setImage(BoxON, for: .selected)
....
Box59.setImage(BoxOFF, for: .normal)
Box59.setImage(BoxON, for: .selected)
}
这是制作尽可能多的复选框所必需的全部代码。但是,每个复选框都需要在故事板上的正确位置创建/移动按钮,并将按钮从故事板上链接到刚刚编码的按钮变量。这可能会花费很多时间,因为每个视图控制器需要100多个按钮。
This is all the code necessary to make as many checkboxes as possible. However, each checkbox requires creating/moving a button to the right spot on the storyboard, linking the button from the storyboard to the button variable that was just coded. This can take a lot of time since I need over 100 buttons per view controller.
是否可以通过制作按钮数组来实现此目的?或类似的东西?
Is there a faster way to do this by making an array of buttons? or something similar?
推荐答案
可以将 IBOutlet
声明为数组
-
创建一个
IBOutlet
作为数组
@IBOutlet var boxes : [UIButton]!
将所有按钮连接到同一插座(按所需顺序)
Connect all buttons to the same outlet (in the desired order)
在 viewDidAppear
中使用循环或 forEach
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
boxes.forEach {
$0.setImage(BoxOFF, for: .normal)
$0.setImage(BoxON, for: .selected)
}
}
为按钮添加唯一标签(可选)。
Add unique tags to the buttons (optional).
使用switch语句按数组中的索引区分按钮,或者通过标签
Use a switch statement to distinguish the buttons by index in the array or by tag
@IBAction func boxTouched(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
let index = boxes.index(of: sender)!
switch index {
// handle the cases
}
}
@IBAction func boxTouched(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
switch sender.tag {
// handle the cases
}
}
这篇关于Swift 4中的UIButton数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!