在Swift

时间:2015-07-28 02:30:32

标签: ios swift button timer stopwatch

我目前正在学习Swift和iOS编程。我学会了创建一个显示秒表的秒表应用程序。我现在尝试将秒表的开始和停止按钮组合在一起。这意味着当应用程序加载时,它会有一个开始按钮,但当我按下开始按钮时,它会变成一个停止按钮,当我按下时,计时器停止,按钮变为开始按钮。我已经搜索过互联网并堆栈溢出,但我找不到类似于我想要的东西。我目前的代码附在下面!

import UIKit

class ViewController: UIViewController {

var timer = NSTimer()

var count = 0.0

func updateTime() {

    count = count + 0.1

    label.text = "\(count)"

}

@IBOutlet weak var label: UILabel!

@IBAction func start(sender: AnyObject) {

    timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: ("updateTime"), userInfo: nil, repeats: true)


    }

@IBAction func pause(sender: AnyObject) {

    timer.invalidate()

}


@IBAction func reset(sender: AnyObject) {

    timer.invalidate()

    count = 0

    label.text = "0"

}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.




}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

1 个答案:

答案 0 :(得分:0)

删除所有IBActions并执行此操作,仅删除操作是不够的,您需要右键单击按钮并断开所有@IBactions以删除完整的引用,否则您将收到错误..

  

//不要使这个@IBAction这只是一个普通的函数

 func start() {
>     timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: ("updateTime"), userInfo: nil, repeats: true)
> 
> 
>     } // smae here... just a function   
     func updateTime() {
> 
>     count = count + 0.1
> 
>     label.text = "\(count)"
> 
> } // same with this just a function 
>        func reset() {
> 
>     timer.invalidate()
> 
>     count = 0
> 
>     label.text = "0"
> 
> }  
> 
> // Now Make a @IBAction to your button , and sender should be UIButton
> 
>

     @IBAction func buttonPressed(sender : UIButton) {   
     if sender.currentTitle == "start" {
    >       sender.setTitle("stop", forState: UIControlState.Normal)
    >       reset() // perform any function that you want to when button is acting as stop button    } 
    else {
    >        sender.setTitle("start", forState: UIControlState.Normal)
    >        start() // perform any function that you want to when button is acting as start button 
    >      } }