Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Shrink Navigation Bar on scroll

I'm really stuck here. I would like to shrink the Navigation Bar when I scroll down a UITableView and enlarge it again when scrolling up. I managed to alter the size of the Navigation Bar, but the title image is not shrinking with the Navigation Bar.

I want to do it exactly like Safari, and the problem is that the height of my TitleView is shrinking but the width never changes.

Here's the code I've used to get the height of the scrollbar to change.

func scrollViewDidScroll(scrollView: UIScrollView) {
    var navbar = navigationController?.navigationBar
    var dir:CGPoint = tableview.panGestureRecognizer.translationInView(self.tableview)
    var scrollViewHeight = tableview.frame.size.height
    var scrollContentSizeHeight = tableview.contentSize.height
    var scrollOffset = tableview.contentOffset.y

    if (dir.y > 0 && self.formernavstate == "small") {
        self.formernavstate = "big"

        UIView.animateWithDuration(0.5, delay:0.0, options: UIViewAnimationOptions.AllowAnimatedContent, animations: { () -> Void in

        println("")
        navbar?.frame.origin.y = 20
        self.navigationItem.titleView?.transform = CGAffineTransformMakeScale(0.52, 0.6)
        }, completion: nil)
    }

    if (dir.y < 0 && self.formernavstate == "big") {
        self.formernavstate = "small"   
        navbar?.frame.origin.y = 0
        navigationItem.titleView?.transform = CGAffineTransformMakeScale(0.0001, 0.2)
    }
}
like image 634
Astu biggi Avatar asked May 05 '15 12:05

Astu biggi


1 Answers

I implemented a Swift 3 version with a custom "header" and resizing it's height constraint based on @chauhan's answer:

extension ViewController: UIScrollViewDelegate {

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollViewOffset < scrollView.contentOffset.y {
            shrinkHeader(shrink: true)
        } else if scrollViewOffset > scrollView.contentOffset.y {
            shrinkHeader(shrink: false)
        }
    }

    func shrinkHeader(shrink: Bool) {
        if shrink {
            if self.headerContainerHeightConstraint.constant > CGFloat(minHeaderHeight) {
                UIView.animate(withDuration: 0.1, animations: {
                    self.headerContainerHeightConstraint.constant = self.headerContainerHeightConstraint.constant - 2
                    self.view.layoutIfNeeded()
                })
            }
        } else {
            if self.headerContainerHeightConstraint.constant < CGFloat(maxHeaderHeight) {
                UIView.animate(withDuration: 0.1, animations: {
                    self.headerContainerHeightConstraint.constant = self.headerContainerHeightConstraint.constant + 6
                    self.view.layoutIfNeeded()
                })
            }
        }
    }
}
like image 89
danywarner Avatar answered Nov 15 '22 01:11

danywarner