本文记录xib在xib中的用法和xib在storybord中的用法探索
1.创建自定义UIView
类名为:TestView
2.创建对应的xib
名称与类TestView
相同
1. 打开xib属性编辑器
设置Size
为 Freeform
2.设置File'S Owner
设置其class
为TestView
3. TestView
类
- 使用
frame
布局如下:
class TestView: UIView {
private var contentView: UIView!
required init?(coder: NSCoder) {
super.init(coder: coder);
}
override init(frame: CGRect) {
super.init(frame: frame)
}
private func setupView() {
contentView = Bundle.main.loadNibNamed("TestView", owner: self, options: nil)?.first as? UIView
addSubview(contentView)
}
override func layoutSubviews() {
super.layoutSubviews()
contentView.frame = bounds
}
}
2.使用SnapKit
布局
⑴安装SnapKit
①打开终端进入项目目录
②输入命令pod init
,执行pod install
③打开JBNib的工作空间,打开Podfile文件
target 'JBNib' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for JBNib
pod 'SnapKit'
end
④再次运行命令行pod install
,等待安装成功
⑵写入布局
import SnapKit
class TestView: UIView {
private var contentView: UIView!
required init?(coder: NSCoder) {
super.init(coder: coder);
}
override init(frame: CGRect) {
super.init(frame: frame)
}
private func setupView() {
contentView = Bundle.main.loadNibNamed("TestView", owner: self, options: nil)?.first as? UIView
addSubview(contentView)
contentView.snp.makeConstraints({
$0.top.left.bottom.right.equalTo(0)
})
}
}
⑶xib中的连线操作
插口变量
class TestView: UIView {
@IBOutlet weak var button: UIButton!
private var contentView: UIView!
required init?(coder: NSCoder) {
super.init(coder: coder);
setupView()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
private func setupView() {
contentView = Bundle.main.loadNibNamed("TestView", owner: self, options: nil)?.first as? UIView
addSubview(contentView)
contentView.snp.makeConstraints({
$0.top.left.bottom.right.equalTo(0)
})
}
@IBAction func doButton(_ sender: Any) {
button.setTitle("click", for: .normal)
}
}
这里需要注意的是在使用
loadNibNamed
方法时,owner
参数必须为self
否则插口变量会报错:
*** Terminating app due to uncaught exception 'NSUnknownKeyException',
reason: '[<NSObject 0x6000008b4510> setValue:forUndefinedKey:]:
this class is not key value coding-compliant for the key button.'
-
使用
拖拽view到置顶控制器上,并更改其class 为 TestView
布局 - 效果
运行截图
点击按钮后
运行截图
网友评论