用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.jianshu.com/p/db3e97ce6190
网友评论