使用不同动作的UIButton
问题描述:
我想要使用不同动作的按钮。当我第一次点击按钮时,只应该更改按钮名称。当我再次点击时,我想显示第一个ViewController。使用不同动作的UIButton
我的问题是,当我第一次点击时,它立即显示第一个ViewController。你能帮我吗?
感谢
@IBAction func startPressed(sender: UIButton) {
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc: ViewController1 = storyboard.instantiateViewControllerWithIdentifier("firstView") as! ViewController1
var m: Bool?
m = true
if (m == true) {
startPressed2.setTitle("Try Again", forState: .Normal)
m = false
}
if (m == false) {
self.presentViewController(vc, animated: true, completion: nil)
}
}
答
有与该代码问题很多。
一个问题是,m
是一个纯粹的局部变量,所以它被创建并设置为true
,新鲜的是,每次调用startPressed
。
取而代之的是,通过声明它为以外的任何方法的来宣传它为实例属性。现在它会一直存在,所以你可以在下一次调用startPressed
时再次检查它。
此外,您的可选在这里是愚蠢的;不要没有理由地使用选项。另外,您可以一次定义和初始化所有内容,并且不需要显式类型。
所以:
var m = true
@IBAction func startPressed(sender: UIButton) {
而且,从来没有一个布尔比较true
或false
;布尔是的条件。你不需要括号。
最后,如果你想要做的时候m
为真时设置标题,那么你就需要停止。你可以做到这一点与return
,或者通过使用else
:
if m {
startPressed2.setTitle("Try Again", forState: .Normal)
m = false
} else {
self.presentViewController(vc, animated: true, completion: nil)
}
答
,因为当你玩你的代码,m = false
语句在执行。首先发生的事情,如果,以后,如果第二个条件是正确的if (m == false)
所以它起到下面的代码。
试试这个:
var m:Bool = true
@IBAction func startPressed(sender: UIButton) {
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc: ViewController1 = storyboard.instantiateViewControllerWithIdentifier("firstView") as! ViewController1
if (m == true) {
startPressed2.setTitle("Try Again", forState: .Normal)
m = false
}else{
self.presentViewController(vc, animated: true, completion: nil)
}
}
如果你不理解的范围和不同类型的变量的一生,看到我的书:http://www.apeth.com/ swiftBook/ch03.html#_variable_scope_and_lifetime – matt
我改变了现在,但我的问题是,当按钮名称改变时,它同时显示视图控制器。我不希望它在同一时间 – Michael
刷新此页面以查看我编辑的答案。 – matt