使用协议XIB加载View

//从Xib中加载View
protocol NibLoadable {
}
extension NibLoadable where Self:UIView  {
    static func loadViewFromNib() -> Self {
        return Bundle.main.loadNibNamed("\(self)", owner: nil, options: nil)?.first as! Self
    }
}
//注册UITableViewCell 
protocol RegisterCellOrNib {
}
extension RegisterCellOrNib {
    static var identifier:String {
        return "\(self)"
    }
    static var nib:UINib? {
        return UINib(nibName: "\(self)", bundle: nil)
    }
}

extension UITableView {

    func registerCell(cell:T.Type) where T:RegisterCellOrNib {
        if let nib = T.nib { register(nib, forCellReuseIdentifier: T.identifier) }
        else { register(cell, forCellReuseIdentifier: T.identifier) }
    }
    /// 从缓存池池出队已经存在的 cell
    func dequeueReusableCell(indexPath: IndexPath) -> T where T: RegisterCellOrNib {
        return dequeueReusableCell(withIdentifier: T.identifier, for: indexPath) as! T
    }
    func reloadRow(at indexPath:IndexPath, with animation: UITableView.RowAnimation) {
        reloadRows(at: [indexPath], with: animation)
    }
}

extension UICollectionView {
    /// 注册 cell 的方法
    func registerCell(cell: T.Type) where T: RegisterCellOrNib {
        if let nib = T.nib { register(nib, forCellWithReuseIdentifier: T.identifier) }
        else { register(cell, forCellWithReuseIdentifier: T.identifier) }
    }
    
    /// 从缓存池池出队已经存在的 cell
    func dequeueReusableCell(indexPath: IndexPath) -> T where T: RegisterCellOrNib {
        return dequeueReusableCell(withReuseIdentifier: T.identifier, for: indexPath) as! T
    }
    
    /// 注册头部
    func registerSupplementaryHeaderView(reusableView: T.Type) where T: RegisterCellOrNib {
        // T 遵守了 RegisterCellOrNib 协议,所以通过 T 就能取出 identifier 这个属性
        if let nib = T.nib {
            register(nib, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: T.identifier)
        } else {
            register(reusableView, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: T.identifier)
        }
    }
    
    /// 获取可重用的头部
    func dequeueReusableSupplementaryHeaderView(indexPath: IndexPath) -> T where T: RegisterCellOrNib {
        return dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: T.identifier, for: indexPath) as! T
    }
}

你可能感兴趣的:(使用协议XIB加载View)