在開發iOS應用時,為了介面美觀,我們通常會建立大量的自訂群組件。而目前Xcode5中的圖形介面開發工具Interface Builder,無法呈現自訂群組件的顯示效果,導致我們為了驗證介面是否符合要求,不得不修改程式的流程,一次次的編譯運行。
在即將到來的Xcode6裡,蘋果提供了自訂群組件的即時渲染功能,稱之為Live Rendering。Live Rendering使我們可以直接在Interface Builder裡看到自訂群組件的視覺效果,避免了需要編譯運行才能驗證效果的流程,大大提高了開發效率。
現在我就簡單的介紹下Live Rendering的使用流程。如果想要使用Live Rendering,自訂群組件必須定義在一個單獨的Framework中(Xcode6現在可以為iOS建立Framework了),自訂群組件的類必須用@IBDesignable來修飾,需要動態即時渲染的屬性需要用@IBInspectable修飾。
樣本:
1.開啟Xcode6建立一個新的工程,選擇項目模板為Single View Application,選擇開發語言為Swift。
2.選擇工程,選擇建立一個新的Target,選擇Cocoa Touch Framework,這裡我們命名Framework的名字為AFK(魔獸玩家會笑吧)
3.在新建立的AFK.framework裡,我們建立一個叫AFKButton的自訂UIButton組件,代碼如下
import UIKit@IBDesignable class AFKButton: UIButton { @IBInspectable var style:NSInteger = 0 { didSet { switch style { case 0: self.backgroundColor = UIColor.blueColor() self.setTitleColor(UIColor.redColor(), forState:UIControlState.Normal) case 1: self.backgroundColor = UIColor.whiteColor() self.setTitleColor(UIColor.blackColor(), forState:UIControlState.Normal) default: self.backgroundColor = UIColor.yellowColor() self.setTitleColor(UIColor.redColor(), forState:UIControlState.Normal) } } } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */}
這裡我們為AFKButton添加了一個可以Live Rendering的屬性:style,在Interface Builder裡通過修改style的值,就可以立即看到效果了。
4.開啟項目模板為我們產生好的Main.storyboard,拽一個Button進來,將它的Class修改成AFKButton,在User defined Runtime Attribute區,添加我們自訂的即時渲染屬性style,將Type設成Number,嘗試修改它的值0、1或者2,就可以直接在Interface Builder裡看到效果了。
Demo工程地址:https://github.com/Guou/LiveRenderingDemo