【发布时间】:2015-12-02 16:26:12
【问题描述】:
我已经成功实现了一个搜索栏,现在我想在向下滑动 tableview 时显示搜索栏,再次向下滑动,隐藏搜索栏。我应该使用什么方法?谢谢
【问题讨论】:
我已经成功实现了一个搜索栏,现在我想在向下滑动 tableview 时显示搜索栏,再次向下滑动,隐藏搜索栏。我应该使用什么方法?谢谢
【问题讨论】:
UITableView 是UIScrollView 的子类,它具有委托方法(来自UIScrollViewDelegate),您可以使用这些方法确定滚动的开始和结束时间。
您可以使用scrollViewDidScroll(_:) 方法在用户开始滚动时得到通知,并在滚动结束时使用scrollViewDidEndDecelerating(_:) 得到通知。
根据您的问题,我假设您已经有了显示/隐藏搜索栏的方法;您只是在寻找“何时”调用您的 showSearchBar 或 hideSearchBar 方法。
您可以拥有一个Bool 属性来存储searchBar 是否隐藏,并相应地调用您的方法。
let searchBarIsHidden = true
override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if searchBarIsHidden {
showSearchBar() //your show search bar function
} else {
hideSearchBar() //your hide search bar function
}
}
现在您应该确保在showSearchBar 和hideSearchBar 的末尾更新searchBarIsHidden 的值
【讨论】:
在 Swift 中使用搜索栏的顶部约束进行漂亮的隐藏和显示:
var lastContentOffset:CGFloat = 0
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let bottomOffset = scrollView.contentSize.height - scrollView.bounds.height
guard scrollView.contentOffset.y < bottomOffset else {
return
}
guard scrollView.contentOffset.y > 0 else {
searchBarTopConstraint.constant = 0
return
}
let offsetDiff = scrollView.contentOffset.y - lastContentOffset
let unsafeNewConstant = searchBarTopConstraint.constant + (offsetDiff > 0 ? -abs(offsetDiff) : abs(offsetDiff))
let minConstant:CGFloat = -searchBar.frame.height
let maxConstant:CGFloat = 0
searchBarTopConstraint.constant = max(minConstant, min(maxConstant, unsafeNewConstant))
lastContentOffset = scrollView.contentOffset.y
}
【讨论】: