2017-05-31 71 views
1

我遇到了很多与此类似的问题,但很多都是针对旧版本的Xcode,或者根本无法使用。 我使用Xcode版本8.3.2(8E2002)和Swift编码语言。我对编码知之甚少,但年轻而且渴望学习! 我正在创建一个clicker game,它可以让你每秒获得游戏币。所以,如果你闲置2分钟,它会给你120美元(每秒120秒120美元)。除此之外,您还可以通过点击主要对象来赚钱。 这里是我到目前为止编码:如何使用Swift添加计时器?

import UIKit 

class ViewController: UIViewController { 

var score = 0 
var add = 1 

func addpersec() { 

    score += 1 
} 
//func used to add to the score based timer. Aka, adding 1 per second 



@IBOutlet weak var scorecount: UILabel! 


@IBAction func clicks(_ sender: Any) { 
    score += 1 
    scorecount.text = "Honey: \(score)" 
} 

@IBOutlet weak var Bees: UITableView! 

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. 
} 


} 
+0

我不知道downvote是什么,似乎是一个合法的问题 – hasen

回答

4
class ViewController: UIViewController { 
    var timer: Timer? = nil // Property 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
     self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(handleTimer), userInfo: nil, repeats: true) 
    } 

    func handleTimer(_ timer: Timer) { 
     print("Timer ticking!") 
    } 
} 

为无效计时器,叫self.timer?.invalidate()

+0

Xcode中指出“的NSTimer”已更名为'定时器' – Traxido

+0

@Traxido然后使用'定时器'。它曾经是'NSTimer',但是很多类已经通过删除来自Objective-C的前缀(比如'NS')来重命名。 –

+0

Thankyou,我是Xcode和swift的新手,所以我不完全理解所有内容,但是另一个错误显示出“使用未解析的标识符'YourViewControllerSubclass'” – Traxido

0

你的问题似乎与到iOS UI,所以我不知道如果我的回答是有道理的。

对于通用延迟功能的执行(如Javascript的setTimeout),你可以使用一个DispatchQueue

// have this as a global somewhere 
let bg = DispatchQueue(label: "bg", qos: .background, target: nil) 

// anywhere else in your code: 

// First decide the time to execute your function 
let delayInSeconds = 3 
let when = DispatchTime.now() + delayInSeconds 

// call it 
bg.asyncAfter(deadline: when) { 
    // code to execute later (this is the body of an anonymous function) 
}