iOS中xib、sb的混合用法(一)

2021-03-17  本文已影响0人  迷路的小小

本文记录xib在xib中的用法和xib在storybord中的用法探索

1.创建自定义UIView

类名为:TestView

2.创建对应的xib

名称与类TestView相同

1. 打开xib属性编辑器

设置SizeFreeform

xib属性
2.设置File'S Owner

设置其classTestView

File'S Owner的属性

3. TestView

  1. 使用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.'
  1. 使用
    拖拽view到置顶控制器上,并更改其class 为 TestView


    布局
  2. 效果
    运行截图
    点击按钮后
    运行截图
上一篇 下一篇

猜你喜欢

热点阅读