SoFunction
Updated on 2025-04-09

iOS development swipe UIScrollview up and down to hide or display instances of navigation bar

1. Many apps have UIScrollview that slides up and down to hide or display the navigation bar. Here I will talk about several methods that I find useful:

1. After iOS8, the system has a property hidesBarsOnSwipe

The Objective-C code is as follows

 = YES; 

Swift code is as follows

?.hidesBarsOnSwipe = true 

When using the above code, the effect can be achieved

2. Use UIScrollViewDelegate a proxy method

The Objective-C code is as follows

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
 //The scrollView already has a drag gesture, and you can directly get the drag gesture of the scrollView UIPanGestureRecognizer *pan = ;
 //Get drag speed >0 Drag down <0 Drag up CGFloat velocity = [pan velocityInView:scrollView].y;
 
 if (velocity &lt;- 5) {
  //Drag upward to hide the navigation bar  [ setNavigationBarHidden:YES animated:YES];
 }else if (velocity &gt; 5) {
  //Drag down to display the navigation bar  [ setNavigationBarHidden:NO animated:YES];
 }else if(velocity == 0){
  //Stop dragging }
}

Swift code is as follows

func scrollViewDidScroll(scrollView: UIScrollView) { 
   
  let pan =  
  let velocity = (scrollView).y 
  if velocity < -5 { 
   ?.setNavigationBarHidden(true, animated: true) 
  } else if velocity > 5 { 
   ?.setNavigationBarHidden(false, animated: true) 
  } 
   
 } 

This effect is the best

3. Use UIScrollViewDelegate another proxy method

The Objective-C code is as follows

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset</span> 
{ 
 if ( > 0.0) { 
  [ setNavigationBarHidden:YES animated:YES]; 
 } else if ( < 0.0){ 
  [ setNavigationBarHidden:NO animated:YES]; 
 } 
} 

Swift code is as follows

func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { 
  if  > 0 { 
   ?.setNavigationBarHidden(true, animated: true) 
  } else if  < 0 { 
   ?.setNavigationBarHidden(false, animated: true) 
  } 
 } 

2. Summary: All three methods are OK. I personally think the second method is the best. You can learn from it.

The above example of sliding up and down UIScrollview to hide or display the navigation bar is the entire content I share with you. I hope you can give you a reference and I hope you can support me more.