[英]One button, 2 action and name change, Swift?
我是这个领域的新手,所以也许我不知道关于Swift的一个非常简单的问题。 我知道如何制作2个用于秒表的按钮,启动和停止。 但是我想使用相同的按钮来启动和停止秒表,然后文本从停止到开始更改,这可能吗?如何?
我能够创建一个满足您要求的简单iOS项目。 这是逐步的。
在项目的Storyboard
创建一个UIViewController
场景,并将其命名为“ ViewController”。 在场景中添加具有一些自动布局约束的UIButton
。 在您的Project Navigator中,使用以下代码创建一个UIViewController
子类文件:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myButton: UIButton!
var timer: NSTimer?
var myInt = 0
var launchBool: Bool = false {
didSet {
if launchBool == true {
myButton.setTitle("Stop", forState: .Normal)
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "fireStopWatch", userInfo: nil, repeats: true)
} else {
myButton.setTitle("Start", forState: .Normal)
timer?.invalidate()
timer = nil
myInt = 0
}
}
}
@IBAction func buttonAction(sender: AnyObject) {
launchBool = !launchBool //true to false, false to true...
}
func fireStopWatch() {
myInt += 1
println(myInt)
}
override func viewDidLoad() {
super.viewDidLoad()
myButton.setTitle("Start", forState: .Normal)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
将您的@IBAction
和@IBOutlet
链接到ViewController场景中的UIButton
。 启动您的项目。
每次单击UIButton
,它都会在“开始”和“停止”之间切换其标题。 每次单击“开始”,它myInt
在Xcode控制台中显示myInt
的递增值。 每次单击“停止”,它都会停止NSTimer
并将myInt
重置为0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.