AppDelegate.swift 文件代码如下:
import UIKit
@UIApplicationMain
class AppDelegate:UIResponder, UIApplicationDelegate {
var window: UIWindow?
var tsLabel: UILabel?
var number: UInt32 =0
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window =UIWindow(frame: UIScreen.mainScreen().bounds)
// Override point for customization after application launch.
self.window!.backgroundColor =UIColor.whiteColor()
self.window!.makeKeyAndVisible()
var num: UInt32 =arc4random();
number = num%100 +1
//创建一个标签
var label = UILabel(frame:CGRectMake(0,20, 320, 50));
label.text ="HoSwift--猜数字"
label.textColor =UIColor.purpleColor()
label.backgroundColor =UIColor.orangeColor();
label.textAlignment =NSTextAlignment.Center;
self.window!.addSubview(label);
//创建一个按钮
var button: UIButton =UIButton.buttonWithType(UIButtonType.System)as UIButton;
button.frame =CGRectMake(230,90, 80, 30);
button.backgroundColor =UIColor.grayColor()
button.layer.cornerRadius =5
button.setTitle("提交",forState:UIControlState.Normal);
button.addTarget(self, action:"buttonClick:", forControlEvents:UIControlEvents.TouchUpInside);
self.window!.addSubview(button);
//创建一个输入框
var textField: UITextField =UITextField(frame: CGRectMake(20, 90, 200, 30))as UITextField
textField.clearsOnBeginEditing =true
textField.text =""
textField.tag =10;
textField.font =UIFont.systemFontOfSize(14);
textField.placeholder ="请输入1~100之间的随机数"
textField.borderStyle = .RoundedRect;
textField.keyboardType = .NumberPad;
self.window!.addSubview(textField);
//创建一个标签
tsLabel = UILabel(frame:CGRectMake(0,140, 320, 50)) as UILabel;
tsLabel!.text ="输入数字请提交"
//包含答案的提示。。
//tsLabel!.text = "输入数字请提交\(number)"
tsLabel!.textColor =UIColor.purpleColor();
tsLabel!.backgroundColor =UIColor.orangeColor();
tsLabel!.textAlignment =NSTextAlignment.Center;
self.window!.addSubview(tsLabel!);
return true
}
func buttonClick(sender: UIButton) {
var textField: UITextField =self.window!.viewWithTag(10)as UITextField;
if textField.text!= "" {
println("\(textField.text)");
var num:UInt32 =UInt32(textField.text.toInt()!)
if num == number {
tsLabel!.text ="恭喜你,猜对了"
}else {
if num < number {
tsLabel!.text ="笨蛋,猜小了"
}else {
tsLabel!.text ="傻瓜,猜大了"
}
}
}else {
var alertView:UIAlertView = UIAlertView()as UIAlertView;
alertView.title ="温馨提示"
alertView.message ="输入的内容不能为空"
alertView.addButtonWithTitle("我知道啦!")
alertView.show();
}
}
override func touchesBegan(touches:NSSet, withEvent event: UIEvent) {
self.window!.endEditing(true);
}
}