运行效果如图所示,仅对个别控件做简单介绍,更多内容可参考Objective-C编程 。
使用Xcode新建Single View Application工程,
在AppleDelegate.swift 文件中添加如下代码:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
var vc = ViewController()
self.window!.rootViewController = vc
self.window!.makeKeyAndVisible()
return true
}
ViewController.swift文件代码如下:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.grayColor()
//创建一个标签
var label = UILabel(frame: CGRectMake(60, 80, 200, 100))
//标签内容
label.text = "HoSwiftUI"
//背景颜色
label.backgroundColor = UIColor.redColor()
//对齐方式 :居中
label.textAlignment = .Center
//显示在当前视图上
self.view.addSubview(label)
//创建一个按钮
var button: UIButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(60, 220, 200, 50)
button.backgroundColor = UIColor.whiteColor()
//设置按钮圆角
button.layer.cornerRadius = 12
button.setTitle("This Is a Button",forState: UIControlState.Normal)
//为按钮绑定事件
button.addTarget(self, action:"buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
//创建一个输入框
var textField: UITextField = UITextField(frame: CGRectMake(60, 300, 200, 30)) as UITextField
textField.text = "HoSwiftUI"
textField.borderStyle = .RoundedRect
self.view.addSubview(textField)
}
//按钮被点击事件
func buttonClick(sender: UIButton){
println("按钮被点击了...");
}
//触摸屏幕收起键盘
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view .endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}