Ios 索引还是标签?用于IBOutletCollection中作为按钮的多个复选框
我对swift有点陌生,但有人提到我应该在IBMoutletCollection中为按钮使用索引或标记 我不知道如何索引或标记特定按钮,然后在下列情况下引用它们:Ios 索引还是标签?用于IBOutletCollection中作为按钮的多个复选框,ios,arrays,swift,button,checkbox,Ios,Arrays,Swift,Button,Checkbox,我对swift有点陌生,但有人提到我应该在IBMoutletCollection中为按钮使用索引或标记 我不知道如何索引或标记特定按钮,然后在下列情况下引用它们: // images of checked and unchecked boxes for the button to switch between var BoxON = UIImage(named: "CheckBox") var BoxOFF = UIImage(named:"UnCheckBox") override func
// images of checked and unchecked boxes for the button to switch between
var BoxON = UIImage(named: "CheckBox")
var BoxOFF = UIImage(named:"UnCheckBox")
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
boxes.forEach {
$0.setImage(BoxOFF, for: .normal)
$0.setImage(BoxON, for: .selected)
}
}
@IBOutlet var boxes : [UIButton]!
@IBAction func boxTouched(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
let index = boxes.index(of: sender)!
switch index {
case 0:
sender.isSelected = !sender.isSelected
case 1:
sender.isSelected = !sender.isSelected
case 2:
sender.isSelected = !sender.isSelected
case 3:
sender.isSelected = !sender.isSelected
case 4:
sender.isSelected = !sender.isSelected
default:
sender.isSelected = !sender.isSelected
}
}
提前感谢!:)
编辑:
卸下开关并替换为if语句(它可以工作!)
单击故事板中的每个按钮,然后在属性检查器中设置标记。这是您应该做的,因为IBOutletCollections不能保证维护订单 然后在代码中,您只需像这样访问标记:sender.tag
@IBAction func clickedButton(_ sender: UIButton) {
switch sender.tag {
case 0:
print("this is button 0")
case 1:
print("this is button 1")
case 2:
print("this is button 2")
default:
print("unknown button")
}
}
在按住ctrl键并将每个按钮拖动到该方法后,这对我有效。在情节提要上,您可以在属性检查器中为每个按钮设置标记。以下是更改后的代码:
@IBAction func boxTouched(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
let buttonTag = sender.tag
switch tag {
case 0:
//code you want to write for case 0
case 1:
//code you want to write for case 1
case 2:
//code you want to write for case 2
case 3:
//code you want to write for case 3
case 4:
//code you want to write for case 4
default:
//code you want to write for default case
}
}谢谢!因此,我更改了标记#,并将switch语句条件更改为sender.tag。不太清楚为什么我的代码不起作用。请确保按住ctrl键并单击所有按钮并将其拖动到iAction方法。是否已正确连接iAction?如果在
boxTouched
方法中放置断点,是否会被击中?此外,将按钮设置为“选中”可能并没有达到预期效果。当可访问性功能打开时,“选中”按钮将使该按钮成为选中按钮,以便向有视觉障碍的iOS用户读取该按钮。是!my sender.isselected处理的案例有误您可能应该演示如何将按钮连接到iAction。您的开关有什么意义?每个案例都会执行相同的操作,实际上会撤消在boxTouched
函数的第一行中所做的更改。是的!谢谢,我刚刚意识到这一点,并通过移除开关并替换为:if sender.isSelected{sender.setImage(BoxOFF,表示:.normal)sender.setImage(BoxON,表示:.selected)}
@IBAction func boxTouched(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
let buttonTag = sender.tag
switch tag {
case 0:
//code you want to write for case 0
case 1:
//code you want to write for case 1
case 2:
//code you want to write for case 2
case 3:
//code you want to write for case 3
case 4:
//code you want to write for case 4
default:
//code you want to write for default case
}