我有一个聊天应用程序,我试图显示当用户滚动到顶部时创建的自定义视图,如果它位于表视图的底部,则也将其隐藏。 (就像whatsapp一样)
说实话,我在“显示/隐藏”按钮的逻辑上苦苦挣扎。 尝试在重新加载数据后立即保存我的tableview的contentOffset.y,所以我会知道它是底部,并且如果它较小以显示自定义视图,但mainTableView.contentOffset.y始终为0。
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if (scrollView == mainTableView) {
print(mainTableView.contentOffset.y)
if let point = startingPointForView {
//where var startingPointForView: CGFloat?
// and tried to save it after I reload the data
//self.startingPointForView = self.mainTableView.contentOffset.y
// but it's always 0
}
// Show and hide button logic
}
}
我想要达到的目标的图像:https://imgur.com/ZkYEi2P
答案 0 :(得分:1)
尝试根据UIscrollview
contentOffset
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let scrollViewContentHeight = scrollView.contentSize.height
let scrollViewHeight = scrollView.frame.height
if scrollView.contentOffset.y < (scrollViewContentHeight - scrollViewHeight){
//Custom view show
}else{
//Custom view Hide
}
}
答案 1 :(得分:0)
也许这段代码会帮助您
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.panGestureRecognizer.translation(in: scrollView).y > 0 {
// down
button.isHidden = false
} else {
// up
button.isHidden = true
}
}
答案 2 :(得分:0)
对于想要在 tableview 滚动时隐藏按钮的人可以使用以下代码:
var previousContentOffset: CGFloat = CGFloat()
扩展 YourViewController:UIScrollViewDelegate{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == self.yourTableView{
let currentContentOffset = scrollView.contentOffset.y
if (currentContentOffset > previousContentOffset) {
// scrolling towards the bottom
if scrollView.contentOffset.y > 50 {
self.yourButton.isHidden = true
} else {
self.yourButton.isHidden = false
}
} else if (currentContentOffset < previousContentOffset) {
// scrolling towards the top
let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height
// Change 10.0 to adjust the distance from bottom
if maximumOffset - currentContentOffset <= 10.0 {
self.yourButton.isHidden = true
} else {
self.yourButton.isHidden = false
}
}
previousContentOffset = currentContentOffset
}
}
}