时间:2021-05-14 10:36:30 | 栏目:iOS代码 | 点击:次
一、好多App都有上下滑动UIScrollview隐藏或者显示导航栏,在这里我说说我觉得有用的几种方法:
1.iOS8之后系统有一个属性hidesBarsOnSwipe
Objective-C代码如下
self.navigationController.hidesBarsOnSwipe = YES;
swift代码如下
self.navigationController?.hidesBarsOnSwipe = true
当使用以上代码时,可以达到效果
2.使用UIScrollViewDelegate一个代理方法
Objective-C代码如下
- (void)scrollViewDidScroll:(UIScrollView *)scrollView { //scrollView已经有拖拽手势,直接拿到scrollView的拖拽手势 UIPanGestureRecognizer *pan = scrollView.panGestureRecognizer; //获取到拖拽的速度 >0 向下拖动 <0 向上拖动 CGFloat velocity = [pan velocityInView:scrollView].y; if (velocity <- 5) { //向上拖动,隐藏导航栏 [self.navigationController setNavigationBarHidden:YES animated:YES]; }else if (velocity > 5) { //向下拖动,显示导航栏 [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另一个代理方法
Objective-C代码如下
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset</span>
{ 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) } }
二、总结:三种方法都可以,我个人觉得第二种方法效果最好,大家可以学习借鉴一下