Self, protocol extension and non-final class

后端 未结 2 2087
时光说笑
时光说笑 2021-01-31 22:04

I tried write a static method for UIView which instantiates view of that class from the nib. Method should be generic and work on every UIView subclasses. Also I wa

2条回答
  •  我在风中等你
    2021-01-31 22:46

    Use following code should be ok(in Swift 3):

    protocol Nibable {}
    extension Nibable {
        static func loadFromNib() -> Self? {
            return Bundle.main.loadNibNamed(String(describing: 
    type(of:Self.self)), owner: nil, options: nil)?.first as? Self
        }
    }
    
    final class ViewFromNib: UIView {}
    extension ViewFromNib: Nibable {}
    
    var nibView = ViewFromNib.loadFromNib()
    

提交回复
热议问题