事情是這樣的….
我新增一個View檔案並設計了畫面,但該怎麼把這個畫面放到我的viewController呢?
新增一個XIB View:
1. XIB檔: File ➜ New ➜ File… ➜ (User Interface) View
2. Swift檔: File ➜ New ➜ File… ➜ (Source)Cocoa Touch Class ➜ Subclass of 擇UIView
3. 到剛剛新增的XIB去把Custom Class內的Class改成剛剛新增的Swift檔
Let’s start!
選擇設計好的XIB檔案,選擇File’s Owner後,把連動的swift的檔案放進去
在swift檔案內新增了一個loadView的方法,傳入XIB畫面的檔案名稱
func loadView(xibViewName:String){
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: xibViewName, bundle: bundle)
let xibView = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
xibView.frame = bounds
self.frame = bounds
self.addSubview(xibView)
}
在XIB的init內調用這個方法
class EditorInfo: UIView {
override init(frame: CGRect){
super.init(frame: frame)
loadXibView(viewName: "EditorInfo")
}
required init?(coder: NSCoder) {
super.init(coder: coder)
loadXibView(viewName: "EditorInfo")
setCollectionViewNib()
}
}
這邊要注意的一點是:你要對畫面做任何的修改設定(例如設定tableView delegate/view導圓角之類),一定要寫在loadXibView之後
指定的UIView的class記得要修改
去viewController內新增一個UIView,把UIView的outlet拉進檔案後,類別應該會自動修改成你設定的class
執行模擬器,就看到做好的畫面出現囉!
額外補充:把預設的XIB畫面修改成可自訂尺寸的狀態
開啟XIB (View)的方式
一般來說,開啟View檔案時,他預設給你的畫面會長得像ViewController,但你可以透過Size並選擇Freeform,改成可自行設定長寬的畫面