2019년 9월 16일 월요일

화면 스크롤시 애니메이션으로 탭바 숨기기


목적 및 의도 
  • 화면(웹뷰)를 아래로 스크롤 하여 탭바를 숨길 때 애니메이션 효과를 주기 
방법 
  • lastOffsetY 변수 선언
  • webview scrollview delegate 선언 
  • delegate method 구현 
내용 
// Mark: ScrollViewDelegate method. 
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
      lastOffsetY = scrollView.contentOffset.y
    }
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
        let hide = scrollView.contentOffset.y > self.lastOffsetY
        if  hide {
            visibleTabBar(isHidden: true)
        } else {
            visibleTabBar(isHidden: false)
        }
    }

// Mark: Custom method
    func visibleTabBar(isHidden: Bool) {
        guard let tabBar = self.tabBarController?.tabBar else {return}
        if tabBar.isHidden == isHidden {
            return
        }
        let frame = tabBar.frame
        let height = tabBar.frame.size.height
        let offsetY = isHidden ? height : -height
        if tabBar.isHidden == true {
          tabBar.isHidden = false
        }
        UIView.animate(withDuration: 0.3, animations: {
            self.tabBarController?.tabBar.frame = frame.offsetBy(dx: 0, dy: offsetY)
        }) { (_) in
            tabBar.isHidden = isHidden
        }
    }

이슈 및 추가 확인 사항 
  • tabBar.isHidden 으로는 애니메이션 효과를 주지 못해 먼저 애니메이션효과와 함께 프레임을 조정한 뒤, isHidden 값을 true 로 변경하였음
  • 스크롤 여부 확인 방법 더 찾아보기: scrollView.panGestureRecognizer.translation(in: scrollView).y <