Swift學(xué)習(xí)之UI開發(fā)初探
概述
Apple近日發(fā)布了Swift編程語言,Swift是供iOS和OS X應(yīng)用編程的新編程語言。相信很多開發(fā)者都在學(xué)習(xí)這門新語言。
廢話不多說,下面我就來學(xué)習(xí)使用Swift創(chuàng)建一個簡單的UI應(yīng)用程序。
關(guān)于Swift語法,可以參考《蘋果Swift編程語言快速上手入門教程》&《蘋果的新編程語言 Swift 簡介》
效果如下:
開發(fā)環(huán)境
Xcode6-beta
iOS 8
創(chuàng)建工程
1. Choose File > New > Project > (iOS or OS X) > Application > your template of choice.
此處選擇 Single view Application。
2. Click the Language pop-up menu and choose Swift.
添加基本控件
在ViewController.swift文件中進行編碼,該文件類似Objective-C的ViewController.m。
UILabel
UILabel 控件常用于顯示文本標(biāo)簽。
下面我們來創(chuàng)建一個label, 查看UILabel類發(fā)現(xiàn)其繼承于UIView, NSCoding。
可以通過類似創(chuàng)建view的方法,設(shè)置大小和lebel的text,通過addSubview方法將其加到當(dāng)前view上。
代碼如下:
- let label = UILabel(frame:CGRect(origin: CGPointMake(10.0, 50.0), size: CGSizeMake(150,50)))//let 是Swift 表示常量的關(guān)鍵字
- label.text = "This is a Label"
- self.view.addSubview(label)
UILabel創(chuàng)建參數(shù)使用了別名,這點像Object-C。
UIButton
UIButton 控件常用于按鈕。
下面我們來創(chuàng)建一個button按鈕,并設(shè)置它的UIControlEvents.TouchUpInside事件的處理,查看UIButton類發(fā)現(xiàn)其繼承于UIControl, NSCoding。
可以通過類似創(chuàng)建view的方法,指定位置和大小創(chuàng)建一個按鈕,然后設(shè)置按鈕的titile,設(shè)置按鈕的背景色,并設(shè)置按鈕的touch事件。
最后通過addSubview方法將其加到當(dāng)前view上。
代碼如下:
- let btn = UIButton(frame:CGRect(origin: CGPointMake(10.0, 110.0), size: CGSizeMake(150,50)))
- btn.setTitle("button", forState: UIControlState.Normal)
- btn.backgroundColor = UIColor.redColor()
- btn.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
- self.view.addSubview(btn)
buttonClick方法實現(xiàn)如下:
- func buttonClick(sender: UIButton!){
- }
UIButton后面的 ”!“ 意味著,sender可以是由UIButton繼承來的任意子類。
UIAlertView
UIAlertView 常用于彈出對話框,下面我們來創(chuàng)建一個alert。
UIAlertView類繼承于UIView,我們先創(chuàng)建了一個alert,然后設(shè)置alert的title、message、button、delegate。
然后調(diào)用UIAlertView的show方法,顯示alert。
我們是在button的touch回調(diào)事件中處理alert的創(chuàng)建和顯示的。在buttonClick方法中添加如下代碼:
- var alert = UIAlertView()
- //直接這樣創(chuàng)建有bug
- //var alert = UIAlertView(title: "alert", message: "this is an alert", delegate: self, cancelButtonTitle: "cancel")
- alert.title = "alert"
- alert.delegate = self
- alert.addButtonWithTitle("cancel")
- alert.message = "this is an alert"
- alert.show()
delegate和self,依然有Object-C的影子。
修改ViewController的聲明,加入UIAlertViewDelegate
- class ViewController: UIViewController, UIAlertViewDelegate
實現(xiàn)alert的delegate方法,處理button的click事件。
- //處理alert 的button click
- func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){
- println("buttonIndex:\(buttonIndex)")
- }
總結(jié)
Swift 的UIKit API接口和 Objective-C的API接口總體上保持一致,熟悉原來的UIKit接口的話,上手Swift UI開發(fā)應(yīng)該很快。
可以通過文檔和API手冊查看各Objective-C的API 如何使用Swift 的API進行編程。
點擊這里獲取本文的Demo。
整理自泰然網(wǎng)(作者:ZeroYang)