美文网首页
一行代码自动适配空白页view(练手Demo)

一行代码自动适配空白页view(练手Demo)

作者: 01_Jack | 来源:发表于2019-10-16 16:14 被阅读0次

前言

Swift终于稳定了,抽空看了遍语法,写个Demo找手感。项目中经常会出现无数据或者无网页面需要适配,so... JKPlaceholderView来了。

表现

placeholder.gif

看点

没什么技术含量,链式配置各参数,基本一行代码可以搞定所需适配页面。此处偷师RXSwift中的写法,优雅的表达方式:

private var jk_placeholder_key: UInt8 = 0

struct JK<T> {
    let base: T
    init(_ base: T) {
        self.base = base
    }
}

protocol JKCompatible {
    associatedtype JKBase
    
    var jk: JK<JKBase> { get set }
}

extension JKCompatible {
    var jk: JK<Self> {
        get {JK(self)}
        set {}
    }
}

extension JK where T: UIView {
    var placeholder: JKPlaceholderView {
        set {
            for view in base.subviews {
                if view is JKPlaceholderView {
                    view.removeFromSuperview()
                }
            }
            objc_setAssociatedObject(base, &jk_placeholder_key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            base.addSubview(newValue)
            reload()
        }
        get {
            objc_getAssociatedObject(base, &jk_placeholder_key) as! JKPlaceholderView
        }
    }
    
    func reload() {
        if let s = base as? UIScrollView {
            base.jk.placeholder.isHidden = s.jk.dataCount() > 0
        } else {
            base.jk.placeholder.isHidden = true
        }
        base.bringSubviewToFront(base.jk.placeholder)
    }
    
    func reload(show: Bool) {
        base.jk.placeholder.isHidden = !show
        base.bringSubviewToFront(base.jk.placeholder)
    }
    
}

extension JK where T: UIScrollView {
    private func dataCount() -> Int {
        var count = 0
        if let tableView = base as? UITableView {
            tableView.reloadData()
            for section in 0..<tableView.numberOfSections {
                count += tableView.numberOfRows(inSection: section)
            }
            
        } else if let collectionView = base as? UICollectionView {
            collectionView.reloadData()
            for section in 0..<collectionView.numberOfSections {
                count += collectionView.numberOfItems(inSection: section)
            }
        }
        return count
    }
}


extension UIView: JKCompatible {}

地址

Demo

相关文章

网友评论

      本文标题:一行代码自动适配空白页view(练手Demo)

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