使用Animation + UIStackView在tableviewSection中更改HeaderView的高度

时间:2019-06-22 11:07:40

标签: ios swift uitableview uistackview uitableviewsectionheader

我有一个Tableview。我在tableview内部插入一个包含2 view(Blue and Gray)和FillEqually的堆栈视图。现在我在隐藏一个视图时遇到问题(蓝色)。另一个视图(灰色)代替了它,并将其放大。隐藏其他视图后,必须更改headerview的高度。我给了UITableView.automaticDimension。下面是示例代码。

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    @IBOutlet weak var tblView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        tblView.delegate = self
        tblView.dataSource = self
        tblView.estimatedSectionHeaderHeight = UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel?.text = "Section \(indexPath.section) Row \(indexPath.row)"

        return cell
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 10
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }



    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

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

        DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
            UIView.animate(withDuration: 1, animations: {
                self.tblView.beginUpdates()
                headerView.view1.isHidden = true
                headerView.stackview.setNeedsLayout()
                headerView.stackview.layoutIfNeeded()
                self.view.setNeedsLayout()
                self.view.layoutIfNeeded()
                self.tblView.endUpdates()
            })

        }
         return headerView
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return UITableView.automaticDimension
    }
}

headerview是一个具有以下代码的xib

class headerView: UIView {
    //initWithFrame to init view from code
    @IBOutlet weak var view2: UIView!
    @IBOutlet weak var stackview: UIStackView!
    @IBOutlet weak var view1: UIView!
    override init(frame: CGRect) {
        super.init(frame: frame)

    }

    //initWithCode to init view from xib or storyboard
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

    }

    //common func to init our view
    private func setupView() {
        backgroundColor = .red
    }
}

HeaderView.Xib中给出的约束

enter image description here

我在这里想要的。例如,view1的高度为30,view2的高度为30,那么stackview和headerview的总高度为60。所以隐藏一个视图后1。 headerview和stackview的总高度仅为30。

0 个答案:

没有答案