调整表格大小后调整滚动

时间:2020-06-14 21:48:24

标签: swift tableview scrollview

我正在使用一种购物车,为此,我使用带按钮的表格视图将产品添加到购物车中。

enter image description here

当用户将产品添加到他们的购物车时,底部会显示一个视图,显示其购买总额。当购物车为空时,视图消失,表格调整为视图大小。

通过更改表格底部约束的值来进行此调整

@objc func hideView(){

    UIView.animate(withDuration: 0.5, animations: {
        self.tableView.layoutIfNeeded()
        self.bottomDistance.constant = 0 //TableView constraint bottom
    })

}
@objc func showView(){
    let padding = UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0.0
    UIView.animate(withDuration: 0.5, animations: {
        self.tableView.layoutIfNeeded()
        self.bottomDistance.constant =  100 + padding
    })
}

一切正常,更新了约束,但隐藏了视图位置的单元格,您必须将其向上移动以便可见。

enter image description here

我可以通过什么方式调整滚动条,使其自动上升,并使整个单元格与底视图对齐。

enter image description here

1 个答案:

答案 0 :(得分:0)

我建议您的子类应该是UIViewController而不是UITableViewController。这样,您可以创建一个UIView,以便UIView的高度为view.frame.height-(您的按钮高度)。然后,将tableView添加为该UIView中的子视图。 然后将按钮的底部约束设置为view.bottomAnchor。这样,您的按钮将停留在页面的底部,并且由于tableView位于您创建的UIView内,因此不会到达该按钮,因此它将一直滚动到该UIView内。

执行以下操作:

let tView = UIView()

then in viewDidLoad():
tView.backgroundColor = .clear

view.addSubView(tView)

//constraint your tView leaving room for the price button at the bottom of the view
tView.anchor(top: view.topAnchor, left: view.leadingAnchor, right: view.trailingAnchor, heightConstant: view.frame.height - (priceButton.frame.height))

tView.addSubView(tableView)

//anchor table view to top, left, right, and bottom of tView

view.addSubView(priceButton)

priceButton.anchor(left: view.leadingAnchor, bottom: view.bottomAnchor, right: view.trailingAnchor)

因此,在这种情况下,您的主视图中有两个视图。 UIView-tView和价格按钮。现在,您的tableView将位于您的tView中,因此它不会干扰按钮。希望这会有所帮助。