【swift代码精简之道】精简xib加载View

通常Xib加载View的两种方法

let v = Bundle.main.loadNibNamed("OurCustomView", owner: nil, options: nil)?.first as! OurCustomView  

或者是

let nib = UINib(nibName: "OurCustomView", bundle: nil)  
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! OurCustomView  

一般一个项目可能多达几十个XIB甚至上百个,那么这样的重复代码是否可以精简一下呢?答案是肯定的

首先把这个重复的动作抽到一个协议中去,并在协议的extension中提供默认实现

代码如下

import Foundation  
  
protocol NibloadProtocol {  
      
}  
  
extension NibloadProtocol where Self : UIView{  
    /* 
    static func loadNib(_ nibNmae :String = "") -> Self{ 
        let nib = nibNmae == "" ? "\(self)" : nibNmae 
        return Bundle.main.loadNibNamed(nib, owner: nil, options: nil)?.first as! Self 
    } 
    */  
    static func loadNib(_ nibNmae :String? = nil) -> Self{  
        return Bundle.main.loadNibNamed(nibNmae ?? "\(self)", owner: nil, options: nil)?.first as! Self  
    }  
}  

xib加载view从此变得如此简单

let v = OurCustomView.loadNib()  

只需要继承该协议即可

原来:
class OurCustomView: UIView {

修改后:

class OurCustomView: UIView,NibloadProtocol {  

使用:

let v = OurCustomView.loadNib()  

code of NibloadProtocol.swift

demo

你可能感兴趣的:(【swift代码精简之道】精简xib加载View)