Swift学习日记004

第一个swift项目(定时点击得分)

代码如下:

import UIKit

class ViewController: UIViewController {
    //秒数
    var second = 0
    //得分
    var score = 0
    let timeLabel = UILabel.init()
    let scoreLabel = UILabel.init()
    //定时器
    var timer = NSTimer.init()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
//UI相关
        SetupUI()
        
        BeginGame()
        
    }
    
    func SetupUI() {
        self.view.backgroundColor = UIColor.greenColor();
        let width = self.view.bounds.size.width
        let height = self.view.bounds.size.height
        
        timeLabel.frame = CGRectMake(width/2-60, 10, 120, 30)
        self.view .addSubview(timeLabel);
        scoreLabel.frame = CGRectMake(width/2-60, height-60, width, 40)
        self.view .addSubview(scoreLabel)
        
        var tapButton = UIButton.init(type: UIButtonType.RoundedRect)
        tapButton.frame = CGRectMake(width/2-60, height/2-20, 120, 40)
        tapButton.backgroundColor = UIColor.whiteColor();
        tapButton.setTitle("Tap me!!", forState: UIControlState.Normal)
        tapButton.addTarget(self, action: #selector(ViewController.TapAction), forControlEvents: UIControlEvents.TouchUpInside)
        
        self.view .addSubview(tapButton)
    }
    
    func BeginGame() {
        second = 30
        score = 0
        timeLabel.text = "TimeLeft:\(second)"
        scoreLabel.text = "Score:\(score)"
        timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.TimeReduce), userInfo: nil, repeats: true)
    }
    
    func TapAction() {
        score  = score+1
        scoreLabel.text = "Score:\(score)"
    }
    
    func TimeReduce() {
        second = second-1
        timeLabel.text = "TimeLeft:\(second)"
        if (second == 0) {
            timer.invalidate()
            var alert = UIAlertController.init(title: "Time's Up", message: "You scored \(score)", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction.init(title: "Try again", style: UIAlertActionStyle.Default, handler: {
                action in self.BeginGame()
            }))
            presentViewController(alert, animated: true, completion: nil)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

你可能感兴趣的:(iOS学习,Swift)