iOS开发上下滑动UIScrollview隐藏或者显示导航栏的实例
一、好多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向上拖动
CGFloatvelocity=[panvelocityInView:scrollView].y;
if(velocity<-5){
//向上拖动,隐藏导航栏
[self.navigationControllersetNavigationBarHidden:YESanimated:YES];
}elseif(velocity>5){
//向下拖动,显示导航栏
[self.navigationControllersetNavigationBarHidden:NOanimated:YES];
}elseif(velocity==0){
//停止拖拽
}
}
swift代码如下
funcscrollViewDidScroll(scrollView:UIScrollView){
letpan=scrollView.panGestureRecognizer
letvelocity=pan.velocityInView(scrollView).y
ifvelocity<-5{
self.navigationController?.setNavigationBarHidden(true,animated:true)
}elseifvelocity>5{
self.navigationController?.setNavigationBarHidden(false,animated:true)
}
}
这种效果最好
3.使用UIScrollViewDelegate另一个代理方法
Objective-C代码如下
-(void)scrollViewWillEndDragging:(UIScrollView*)scrollViewwithVelocity:(CGPoint)velocitytargetContentOffset:(inoutCGPoint*)targetContentOffset
{
if(velocity.y>0.0){
[self.navigationControllersetNavigationBarHidden:YESanimated:YES];
}elseif(velocity.y<0.0){
[self.navigationControllersetNavigationBarHidden:NOanimated:YES];
}
}
swift代码如下
funcscrollViewWillEndDragging(scrollView:UIScrollView,withVelocityvelocity:CGPoint,targetContentOffset:UnsafeMutablePointer){ ifvelocity.y>0{ self.navigationController?.setNavigationBarHidden(true,animated:true) }elseifvelocity.y<0{ self.navigationController?.setNavigationBarHidden(false,animated:true) } }
二、总结:三种方法都可以,我个人觉得第二种方法效果最好,大家可以学习借鉴一下
以上这篇iOS开发上下滑动UIScrollview隐藏或者显示导航栏的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。