美文网首页
小知识五、Cell reuseIdentifier用自己类做重用

小知识五、Cell reuseIdentifier用自己类做重用

作者: ISwiftUI | 来源:发表于2017-02-24 15:08 被阅读27次
import Foundation
import UIKit

protocol ViewNameReusable:class { }

extension ViewNameReusable where Self: UIView {
    static var reuseIdentifier: String {
        return String(describing: self)
    }
}

extension UICollectionView {
    
    func dequeueReusableCell<T: UICollectionViewCell>(forIndexPath indexPath: IndexPath) -> T where T: ViewNameReusable {
        guard let cell = dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
            fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)")
        }
        return cell
    }
    
    func dequeueReusableSupplementaryView<T: UICollectionReusableView> (kind: String, forIndexPath indexPath: IndexPath) -> T where T: ViewNameReusable {
        guard let headerCell = dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
            fatalError("Could not dequeue ReusableView with identifier: \(T.reuseIdentifier)")
        }
        return headerCell
    }
}

extension UITableView {
    func dequeueReusableCell<T: UITableViewCell>(forIndexPath indexPath: IndexPath) -> T where T: ViewNameReusable {
        guard let cell = dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
            fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)")
        }
        return cell
    }
}

相关文章

网友评论

      本文标题:小知识五、Cell reuseIdentifier用自己类做重用

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