美文网首页2017Swift编程iOS Developer
动态改变TableView Header View的高度

动态改变TableView Header View的高度

作者: ASAJ | 来源:发表于2017-04-26 08:58 被阅读463次

    首先HeaderView 和一般的Cell的区别在于headerView不会随着tableview的滚动而消失,会一直停留在屏幕最上端。所以,对于这种需求的时候,headerView是不可以简单用普通cell替换的。我们假设在header view里面有一个下载的progress bar,点击开关以后就开始显示这个bar,如下图:


    out.gif

    那么很显然,我们的header view是需要根据开关是否开启而变化高度的,问题在于TableView并没有一个能够reload headerView的方法可以调用。常见的解决思路有两种:
    1. reload整个section
    2. 不复用Header View
    对于比较简单的小型demo或者poc,这两种解决方案是可以考虑使用的,但是对于比较复杂的大型项目,特别是reload section开销非常大的项目,那么以上两种方案肯定都是不可以接受的。那么有没有直接reload header view的方法呢?直接答案是没有,但是,有一个方案可以达到类似效果:

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            for header in headers {
                guard delegate!.headerContainer != nil else {return UITableViewAutomaticDimension}
                if object_getClassName(header.type) == object_getClassName(delegate!.headerContainer![section]) {
                    return header.viewHight
                }
            }
            return UITableViewAutomaticDimension
        }
        
        func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            for header in headers {
                guard delegate!.headerContainer![section] != nil else {return nil}
                header.updateData(delegate!.headerContainer![section]!)
                var hView = tableView.dequeueReusableHeaderFooterView(withIdentifier: header.identifier) as? GenericHeaderView
                if hView == nil {
                    hView = UINib(nibName: header.identifier, bundle: nil).instantiate(withOwner: nil, options: nil)[0] as? GenericHeaderView
                }
                hView?.configureHeaderView(t: header)
                hView?.section = section
                hView?.updateHandler = { index in
                    let temp = tableView.headerView(forSection: index) as! GenericHeaderView
                    DispatchQueue.main.async {
                        tableView.beginUpdates()
                        temp.updateUI()
                        tableView.endUpdates()
                        
                    }
                }
                return hView
            }
            return nil
        }
    

    去除掉不重要的信息,其实核心的部分是:

    DispatchQueue.main.async {
                        tableView.beginUpdates()
                        temp.updateUI()
                        tableView.endUpdates()
                        
                    }
    
    override func updateUI() {
            if !reverse {
                self.top.constant = -2
                self.progress.isHidden = true
            }else {
                self.top.constant = 8
                self.progress.isHidden = false
                countDown()
            }
        }
    

    让我们看一下如何在MVVM module里面增加处理动态改变高度的能力:
    首先我们需要在TableFactory.swift里面增加类似cell的抽象类:

    class GenericHeaderView:UITableViewHeaderFooterView {
        var section = 0
        var updateHandler:((Int)->Void)!
        
        func configureHeaderView<T>(t:T){}
        func updateUI(){}
    }
    

    这个类将成为所有Header View的父类,提供两个需要被override的方法来提供改变高度的方法(强制改变高度或者改变其他constrain,示例是通过改变constrain的方法来改变header高度的)。然后在TableFactory class里面增加一个headerContainer来储存所有header的类型以及相应的注册方法:

    fileprivate var headers:[FactoryViewDataSource] = [FactoryViewDataSource]()
    
    func registerHeader(header:FactoryViewDataSource) -> FactoryViewDataSource {
            let existed = headers.filter {object_getClassName($0.identifier) == object_getClassName(header.identifier)}
            if existed.isEmpty {
                headers.append(header)
                return header
            }else {
                return existed.first!
            }
        }
    

    到此为止我们ViewModel用了能够提供Header View类型和对应section的能力,我们就可以直接使用UITableViewDelegate里面的相关方法了:

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            for header in headers {
                guard delegate!.headerContainer != nil else {return UITableViewAutomaticDimension}
                if object_getClassName(header.type) == object_getClassName(delegate!.headerContainer![section]) {
                    return header.viewHight
                }
            }
            //Line 98 will cause an empty gray header, if you dont want any headerView, set 0
            return UITableViewAutomaticDimension
        }
        
        func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            for header in headers {
                guard delegate!.headerContainer![section] != nil else {return nil}
                header.updateData(delegate!.headerContainer![section]!)
                var hView = tableView.dequeueReusableHeaderFooterView(withIdentifier: header.identifier) as? GenericHeaderView
                if hView == nil {
                    hView = UINib(nibName: header.identifier, bundle: nil).instantiate(withOwner: nil, options: nil)[0] as? GenericHeaderView
                }
                hView?.configureHeaderView(t: header)
                hView?.section = section
                hView?.updateHandler = { index in
                    let temp = tableView.headerView(forSection: index) as! GenericHeaderView
                    DispatchQueue.main.async {
                        tableView.beginUpdates()
                        temp.updateUI()
                        tableView.endUpdates()
                        
                    }
                }
                return hView
            }
            return nil
        }
    

    我们整个Module到这里就配置好了,当我们创建了ViewModel和HeaderView以后就可以直接在ViewController里面使用了:

    var headerContainer:[Any?]?{
            return [
                "Nightmare Trigger",
                nil,
                "Good Dream Trigger"
            ]
        }
    override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            let vm = TableFactory.shared.registerViewModel(vm: ContentCellVM()) as! ContentCellVM
            vm.delegate = self
            
            let _ = TableFactory.shared.registerHeader(header: HeaderVM())
        }
    

    完整的project可以在这里被找到:https://github.com/LHLL/MVVMSample
    UICollectionView/UITableView MVVM Module的解释说明:http://www.jianshu.com/p/a42186dfab1b

    相关文章

      网友评论

        本文标题:动态改变TableView Header View的高度

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