美文网首页程序员
swift xib创建view时实例化

swift xib创建view时实例化

作者: 心猿意码_ | 来源:发表于2022-06-17 11:24 被阅读0次
    方式一
    • Xib 自定义View实例化
    class MyClass: UIView {        
        class func instanceFromNib() -> UIView {
            return UINib(nibName:"nib file name", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as UIView
        }    
    }
    
    • 使用
    var view = MyClass.instanceFromNib()
    view.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
    self.view.addSubview(view)
    
    方式二
    • 创建Bundle的通用方法
    extension Bundle {
    
        static func loadView<T>(fromNib name: String, withType type: T.Type) -> T {
            if let view = Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as? T {
                return view
            }
    
            fatalError("Could not load view with type " + String(describing: type))
        }
    }
    
    • 使用方式1
    let myView = Bundle.loadView(fromNib: "MyClass", withType: MyClass.self)
    
    • 使用方式2
    class MyClass: UIView {        
        class func loadView() -> UIView {
            return Bundle.loadView(fromNib: "MyClass", withType: MyClass.self)
        }  
    }
    
    var view = MyClass.loadView()
    view.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
    self.view.addSubview(view)
    

    注意:

    MyClass.swift 文件中重写
    
    required init?(coder:NSCoder) {
        super.init(coder: coder)
    }
    
    如下方式重写会报错: Thread 1: Fatal error: init(coder:) has not been implemented
    
    required init?(coder:NSCoder) {
            fatalError("init(coder:) has not been implemented")
     }
    

    相关文章

      网友评论

        本文标题:swift xib创建view时实例化

        本文链接:https://www.haomeiwen.com/subject/ltocvrtx.html