用xib文件可以用可視化的方式自定義個View,十分方便。
1.創建一個xib文件
選擇 File->New->File
在iOS下的 User Interface 中選擇 View, 單擊 Next。
這里我起名字叫:MyView.xib
在xib文件中,你可以自己定義想要的視圖效果,例如綠色的背景,中間在正中央有一行文字:
2.創建一個swift類
選擇 File->New->File
在iOS下的 User Interface 中選擇 Cocoa Touch Class, 單擊 Next。
名字與上面一致:MyView,繼承自UIView,語言選擇swift,單擊Next。
3.關聯xib文件與swift文件
選中 placeholders 中的 show the Identity inspector,修改Custom Class 中的 Class,是你創建的swift類的名字。
單擊1處,打開 Show the Assistant editor(助手編輯器),在2處按住control,按住鼠標左鍵拖拽到3處后松手,取名叫content。
關聯完成后,會多處這樣一行代碼:
@IBOutlet var content: UIView!
4. 修改對應swift類中的代碼
整個代碼文件應該是這樣的:
import UIKit
class MyView: UIView {
@IBOutlet var content: UIView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initFromXIB()
}
override init(frame: CGRect) {
super.init(frame: frame)
initFromXIB()
}
func initFromXIB() {
let bundle = Bundle(for: type(of: self))
//nibName是你定義的xib文件名
let nib = UINib(nibName: "MyView", bundle: bundle)
content = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
content.frame = bounds
self.addSubview(content)
}
}
5.在storyboard中調用xib
向storyboard中的ViewControler拖入一個View,設置類為MyView。
運行一下,就能在紅色區域的地方看到我們自定義的視圖了。
6.在storyboard看到xib中的內容。
只需要在定義的swift中,加入一句話即可實現在storyboard中看到xib文件的內容:@IBDesignable
@IBDesignable
class MyView: UIView {
//...后面內容省略
這是Xcode中的實時渲染效果,相關信息可以參照這篇文章: http://www.lxweimin.com/p/db3e97ce6190