新建iOS single view application 名字为whatNumber,打开main storyboard选中view controoler,右上角,attribute inspector中simulated metrics 的size 选择iphone 4.7-inch这样view controller更像是一个iphone..
然后拖动三个控件到界面上lable,text field,button
最后打开assistant editor,ctrl 拖动这三个控件到viewController.swift中,会自动生成如下代码
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var guessField: UITextField!
@IBAction func checkBtnPressed(sender: UIButton) {
完整的代码如下:
// // ViewController.swift // whatNumber // // Created by cyper on 6/2/16. // Copyright © 2016 Moaz Tech. All rights reserved. // import UIKit class ViewController: UIViewController { let randomNum = arc4random_uniform(5) @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var guessField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view,typically from a nib. print(randomNum) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func checkBtnPressed(sender: UIButton) { let userEntered = guessField.text let generated = String(randomNum) guessField.text = "" if userEntered == generated { resultLabel.text = "Correct Answer" resultLabel.textColor = UIColor.greenColor() } else { resultLabel.text = "Incorrect! Try Again." resultLabel.textColor = UIColor.redColor() } } }
学到的:
在Attribute inspector中可以设置text field的Keyboard type为Number Pad,这样当text field获得焦点时弹出的就是数字键盘.
设置文本的颜色:resultLabel.textColor = UIColor.redColor()
生成随机数用func arc4random_uniform(_: UInt32) -> UInt32,比如arc4random_uniform(5)可以生成0~4的随机数字,依此类推.