Ben
Ben

Reputation: 428

How to make custom label as UINavBar disappear when scrolling down a table view?

I have recently implemented a custom UINavigationBar in my app that uses a label instead of the normal largeTitle. I have been trying to make this disappear when the user scrolls down the table view.

So far I have tried to set label.isHidden = true when the third cell is displayed as that is the next cell not on the original page and so indicates a scroll. However this means that the label does not disappear until a certain amount has been scrolled.

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    if indexPath == 2 {

        label.isHidden = true

    }

}

Instead, I would like this custom navBar label to be hidden as soon as scrolling begins and to reappear when scrolling comes back to the top just like the default UINavigationBar does.

Thanks.

Upvotes: 1

Views: 80

Answers (1)

Bhavik Modi
Bhavik Modi

Reputation: 1565

You can try following code:

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    if(velocity.y > 0) {
        self.navLabel.isHidden = true
    } else {
        self.navLabel.isHidden = false
    }
}

Or If you want animation same as UINavigationBar Hide / Show, use the following code:

 func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        if(velocity.y > 0) {

            UIView.animate(withDuration: 0.5, delay: 0, options: UIView.AnimationOptions(), animations: {
                let labelFrame = self.navLabel.frame
                self.navLabel.frame = CGRect(x: labelFrame.origin.x, y: -64, width: labelFrame.size.width, height: labelFrame.size.height)
            }, completion: nil)

        } else {
            UIView.animate(withDuration: 0.5, delay: 0, options: UIView.AnimationOptions(), animations: {
                let labelFrame = self.navLabel.frame
                self.navLabel.frame = CGRect(x: labelFrame.origin.x, y: 0, width: labelFrame.size.width, height: labelFrame.size.height)
            }, completion: nil)
        }
    }

Upvotes: 1

Related Questions