我是这个领域的新手,所以可能是一个非常简单的问题,我不知道,关于 swift。我知道如何制作 2 个用于秒表的按钮,启动和停止。但我希望有相同的按钮来启动和停止秒表,然后文本从停止变为开始,这可能吗?如何实现?
最佳答案
我能够创建一个符合您要求的简单 iOS 项目。这是一步一步的。
在项目的 Storyboard
中创建一个 UIViewController
场景,并将其命名为“ViewController”。在您的场景中添加一个带有一些自动布局约束的 UIButton
。在您的项目导航器中,创建一个包含以下代码的 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
时,它的标题都会在“开始”和“停止”之间切换。每次单击“开始”时,它都会在 Xcode 控制台中显示 myInt
的递增值。每次您点击“停止”时,它都会停止您的 NSTimer
并将 myInt
重置为 0。
关于button - 一个按钮,两个 Action 和名称更改,Swift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25770008/