Swift學(xué)習(xí)之UI開(kāi)發(fā)初探
概述
Apple近日發(fā)布了Swift編程語(yǔ)言,Swift是供iOS和OS X應(yīng)用編程的新編程語(yǔ)言。相信很多開(kāi)發(fā)者都在學(xué)習(xí)這門(mén)新語(yǔ)言。
廢話不多說(shuō),下面我就來(lái)學(xué)習(xí)使用Swift創(chuàng)建一個(gè)簡(jiǎn)單的UI應(yīng)用程序。
關(guān)于Swift語(yǔ)法,可以參考《蘋(píng)果Swift編程語(yǔ)言快速上手入門(mén)教程》&《蘋(píng)果的新編程語(yǔ)言 Swift 簡(jiǎn)介》
效果如下:
開(kāi)發(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文件中進(jìn)行編碼,該文件類似Objective-C的ViewController.m。
UILabel
UILabel 控件常用于顯示文本標(biāo)簽。
下面我們來(lái)創(chuàng)建一個(gè)label, 查看UILabel類發(fā)現(xiàn)其繼承于UIView, NSCoding。
可以通過(guò)類似創(chuàng)建view的方法,設(shè)置大小和lebel的text,通過(guò)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ù)使用了別名,這點(diǎn)像Object-C。
UIButton
UIButton 控件常用于按鈕。
下面我們來(lái)創(chuàng)建一個(gè)button按鈕,并設(shè)置它的UIControlEvents.TouchUpInside事件的處理,查看UIButton類發(fā)現(xiàn)其繼承于UIControl, NSCoding。
可以通過(guò)類似創(chuàng)建view的方法,指定位置和大小創(chuàng)建一個(gè)按鈕,然后設(shè)置按鈕的titile,設(shè)置按鈕的背景色,并設(shè)置按鈕的touch事件。
最后通過(guò)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方法實(shí)現(xiàn)如下:
- func buttonClick(sender: UIButton!){
- }
UIButton后面的 ”!“ 意味著,sender可以是由UIButton繼承來(lái)的任意子類。
UIAlertView
UIAlertView 常用于彈出對(duì)話框,下面我們來(lái)創(chuàng)建一個(gè)alert。
UIAlertView類繼承于UIView,我們先創(chuàng)建了一個(gè)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的聲明,加入U(xiǎn)IAlertViewDelegate
- class ViewController: UIViewController, UIAlertViewDelegate
實(shí)現(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接口總體上保持一致,熟悉原來(lái)的UIKit接口的話,上手Swift UI開(kāi)發(fā)應(yīng)該很快。
可以通過(guò)文檔和API手冊(cè)查看各Objective-C的API 如何使用Swift 的API進(jìn)行編程。
點(diǎn)擊這里獲取本文的Demo。
整理自泰然網(wǎng)(作者:ZeroYang)