Swift下自定义xib添加到Storyboard
xcode,swift,xib,storyboard,布局2016-06-13
猴子原创,欢迎转载。转载请注明: 转载自Cocos2Der-CSDN,谢谢!
原文地址: http://blog.csdn.net/cocos2der/article/details/51657154
我们使用Storyboard布局的时候,很多子单元页面会独立到xib布局中,那么这个xib如何添加到storyboard中呢?下面我们看看Swift下怎么操作。
@IBOutlet var view: UIView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// app 运行后从storyboard加载
NSBundle.mainBundle().loadNibNamed(
String(MyView),
owner: self,
options: nil
)[0] as! UIView
self.addSubview(view)
view.frame = self.bounds
self.setup()
}
func setup() {
// init code ...
}
OK, 现在运行Xcode,是不是看到app运行后,自己的xib已经出来了。
细心的朋友注意到了,Main.storyboard中没有刷新xib视图,只能运行后才能看到,下面我们让Main.storyboard中也能预览xib。
1. 添加@IBDesignable属性
2. 添加Main.storyboard下xib初始化方法
3. 注意:
- Xcode非运行状态下storyboard加载xib使用NSBundle.mainBundle().loadNibNamed会出现找不到xib文件的错误。
- xib加载后,需要设置其frame大小,不然frame会是xib中的大小。
- 每次选中storyboard,都会自动Build一次来刷新其中xib视图,如果过程中出现错误信息可以直接Xcode下查看,如果出现Crash错误,Xcode下不会显示,此时去查看下面的crash文件来帮助你定位问题。
~/Library/Logs/DiagnosticReports/IBDesignablesxxxxxxx.crash
下面是完整MyView.swift
import UIKit
@IBDesignable class MyView: UIView {
@IBOutlet var view: UIView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// app 运行后从storyboard加载
NSBundle.mainBundle().loadNibNamed(
String(MyView),
owner: self,
options: nil
)[0] as! UIView
self.addSubview(view)
view.frame = self.bounds
self.setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
// Xcode中storyboard预览加载
NSBundle(forClass: MyView.self).loadNibNamed(
String(MyView),
owner: self,
options: nil
)[0] as! UIView
self.addSubview(view)
view.frame = self.bounds
self.setup()
}
func setup() {
// init code ...
}
@IBAction func tapped(sender: AnyObject) {
print("tappd")
}
}
效果图: