首页 > 解决方案 > 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.

标签: iosswiftuinavigationcontrolleruilabeluinavigationbar

解决方案


您可以尝试以下代码:

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

或者,如果您想要与 UINavigationBar Hide / Show 相同的动画,请使用以下代码:

 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)
        }
    }

推荐阅读