Swift:按钮没有响应tap

时间:2015-07-19 14:46:33

标签: ios swift

嘿所以我是编码的新手,我在View Controller上放了一个按钮(拖放)。按钮没有响应触摸或任何东西,并显示为“静态”。我累了,筋疲力尽。有人帮忙吗?非常感谢你!

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var lbl1: UILabel!
    @IBOutlet weak var lblMadeToday: UILabel!

    @IBOutlet weak var Cents: UILabel!
    var timer = NSTimer()
    var hourlyWage : CGFloat = CGFloat (hourlyPrice)
    var timeTo1 : CGFloat = 0
    var time : Float = 0
    var earnt : CGFloat = 0
    var madeToday : CGFloat = 0

    @IBAction func btnClick(sender: AnyObject) {

    }

    func tick() {
     earnt = CGFloat (time)/timeTo1
     lbl1.text = NSString(format: "%.2f", earnt) as String


        if (earnt >= 1) {
            time = 0
            madeToday++
            lblMadeToday.text = madeToday.description
        }
        time++
    }


    override func viewDidLoad() {
        super.viewDidLoad()
       timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("tick"), userInfo: nil, repeats: true)
        timeTo1 = CGFloat (360000)/hourlyWage;

        println("view Loaded :)")
       NSNotificationCenter.defaultCenter().addObserver(self, selector:"doYourStuff", name:
            UIApplicationWillEnterForegroundNotification, object: nil)
    }


    func doYourStuff(){
        var nowHour = NSCalendar.currentCalendar().component(.CalendarUnitHour, fromDate: NSDate())
        var nowMinute = NSCalendar.currentCalendar().component(.CalendarUnitMinute, fromDate: NSDate())
        var nowSecond = NSCalendar.currentCalendar().component(.CalendarUnitSecond, fromDate: NSDate())

        var time1 = (nowHour - globalHour) * 60
        var time2 = (nowMinute - globalMinute)
        var time3 : CGFloat  = (CGFloat(nowSecond)-CGFloat(globalSecond))/60
        var timeInMinutesGone : CGFloat = CGFloat(time1) + CGFloat(time2) + CGFloat(time3)
        println (timeInMinutesGone)
        madeToday = (timeInMinutesGone / 60) * (CGFloat(hourlyWage))
        var ef : Int = Int(madeToday)
        lblMadeToday.text = String(ef)
    }

    @IBAction func btnPress(sender: AnyObject) {
        println("hello")
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

1 个答案:

答案 0 :(得分:0)

您的NSTimer每0.01秒在UI线程中执行一次。这可能对您的应用程序有害。如果你在后台线程中执行NSTimer,你的按钮可能会按预期工作。

将NSTimer添加到后台的一种方法可能是:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in

    let timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("tick"), userInfo: nil, repeats: true)
    NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
    NSRunLoop.currentRunLoop().run()
})