我有4个按钮调用一个功能。根据按下哪个按钮,我需要隐藏按下后调用的功能内部的按钮。我不知道按下了哪个按钮,所以我试图为4个按钮中的每一个分配标签,以便通过标签识别它们并使用开关
我试过这个
switch sender.tag {
case 1:
self.button1.hidden = true
case 2:
self.button2.hidden = true
case 3:
self.button3.hidden = true
case 4:
self.button4.hidden = true
}
但这不起作用编译器说使用未解析的标识符'sender'
如何正确地做到这一点?
编辑:
整个功能
if self.allowMistakeVar {
let mistakeAlert = UIAlertController(title: "Here is title!", message: "message of alert", preferredStyle: .Alert)
let okay = UIAlertAction(title: "OK", style: .Cancel) { UIAlertAction in
self.allowMistakeVar = false
self.allowMistakeButton.enabled = false
switch sender.tag {
case answer1Text:
self.answer1Text.hidden = true
case answer2Text:
self.answer2Text.hidden = true
case answer3Text:
self.answer3Text.hidden = true
case answer4Text:
self.answer4Text.hidden = true
}
}
mistakeAlert.addAction(okay)
self.presentViewController(mistakeAlert, animated: true, completion: nil )
} else {
另一个案例.. }
答案 0 :(得分:10)
为什么你总是想用标签来确定UIButton?如果被调用函数有一个sender参数,那么你就知道通过这个参数调用函数的UIButton。
func buttonClicked(sender: UIButton)
{
switch sender {
case button1: // Do something
case button2: // Do some other stuff
...
default: ()
}
}
答案 1 :(得分:10)
试试这个,
1)为每个按钮分配标签
Button1.tag=1
Button2.tag=2
Button3.tag=3
Button4.tag=4
2)然后检查您的常用按钮操作
func buttonClicked(sender: UIButton)
{
switch sender.tag {
case 1: self.sender.hidden = true //button1
break;
case 2: self.sender.hidden = true //button2
break;
case 3: self.sender.hidden = true //button3
break;
case 4: self.sender.hidden = true //button4
break;
default: ()
break;
}
}
答案 2 :(得分:4)
将您的代码放入如下所示的代码中:
func btnSomeButtonClicked(sender: UIButton)
{
let tag = sender.tag;
//put your same code here and either use tag variable as i shown or put as you did.
}
- >因此,您将很容易获得发件人的财产。
- >同时检查您是否忘记为UIButtons提供标签。
答案 3 :(得分:1)
I know this has been answered, but if you set this up in IB, then I would recommend you check if the button was pressed by using the @IBOutlet variables as cases.
class SomeView: UIView {
@IBOutlet weak var buttonA: UIButton!
@IBOutlet weak var buttonB: UIButton!
@IBOutlet weak var buttonC: UIButton!
@IBAction func didHitButton(_ sender: UIButton) {
switch sender {
case buttonA:
doThis()
}
case buttonB:
doThat()
}
case buttonC:
doThisAgain()
}
default:
doNothing()
}
}
...
}
Now you hook up the buttons in your NIB to each @IBOutlet, and all of the buttons to the one @IBAction didHitButton.
This is pretty straight forward, and you don't have to worry about tags or changing names.
答案 4 :(得分:0)
而不是使用switch语句,您可以直接使用发件人。
请注意,您需要指定发件人是UIButton(因此,只有在仅从按钮调用该函数时才会这样做。)
@IBAction func submitButton(sender: UIButton) {
/* extra code here */
sender.enabled = false
}
这样可以减少代码,还可以在不更改代码的情况下添加额外的按钮。