原文
一、好多App都有上下滑動(dòng)UIScrollview隱藏或者顯示導(dǎo)航欄,在這里我說(shuō)說(shuō)我覺(jué)得有用的幾種方法:
1.iOS8之后系統(tǒng)有一個(gè)屬性hidesBarsOnSwipe
Objective-C代碼如下
self.navigationController.hidesBarsOnSwipe = YES;
swift代碼如下
self.navigationController?.hidesBarsOnSwipe = true
當(dāng)使用以上代碼時(shí),可以達(dá)到效果
2.使用UIScrollViewDelegate一個(gè)代理方法
Objective-C代碼如下
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//scrollView已經(jīng)有拖拽手勢(shì)兢仰,直接拿到scrollView的拖拽手勢(shì)
UIPanGestureRecognizer *pan = scrollView.panGestureRecognizer;
//獲取到拖拽的速度 >0 向下拖動(dòng) <0 向上拖動(dòng)
CGFloat velocity = [pan velocityInView:scrollView].y;
if (velocity <- 5) {
//向上拖動(dòng)已艰,隱藏導(dǎo)航欄
[self.navigationController setNavigationBarHidden:YES animated:YES];
}else if (velocity > 5) {
//向下拖動(dòng)祟滴,顯示導(dǎo)航欄
[self.navigationController setNavigationBarHidden:NO animated:YES];
}else if(velocity == 0){
//停止拖拽
}
}
swift代碼如下
func scrollViewDidScroll(scrollView: UIScrollView) {
let pan = scrollView.panGestureRecognizer
let velocity = pan.velocityInView(scrollView).y
if velocity < -5 {
self.navigationController?.setNavigationBarHidden(true, animated: true)
} else if velocity > 5 {
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
這種效果最好
3.使用UIScrollViewDelegate另一個(gè)代理方法
Objective-C代碼如下
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
if (velocity.y > 0.0) {
[self.navigationController setNavigationBarHidden:YES animated:YES];
} else if (velocity.y < 0.0){
[self.navigationController setNavigationBarHidden:NO animated:YES];
}
swift代碼如下
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if velocity.y > 0 {
self.navigationController?.setNavigationBarHidden(true, animated: true)
} else if velocity.y < 0 {
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
二刊懈、總結(jié):三種方法都可以,我個(gè)人覺(jué)得第二種方法效果最好,大家可以學(xué)習(xí)借鑒一下