简体   繁体   中英

Changing navigationBar's title based on position in scrollView

I'm trying to change the navigationBar's title based on a scrollView's x position. Here's the code I have. I don't know why it's not working or if it's possible though:

if(scrollView.contentOffset.x == 0) {
            self.navigationController!.navigationBar.topItem!.title = "First"
        }
        else if(scrollView.contentOffset.x == self.view.frame.size.width) {
            self.navigationController!.navigationBar.topItem!.title = "Second"
        }
        else if(scrollView.contentOffset.x == self.view.frame.size.width*2) {
            self.navigationController!.navigationBar.topItem!.title = "Third"
        }

Any ideas as to what's going wrong? I put this in the viewDidLoad of the ViewController the scrollView is in. It's only setting the navigationBar's title as "First". Is it because I put in viewDidLoad? Do I have to put it into a new method that updates?

I also tried putting the following code in, updating when the scrollView ended dragging. This does not change anything though:

func scrollViewDidEndDragging(scrollView: UIScrollView!, willDecelerate decelerate: Bool) {
        if(self.scrollView.contentOffset.x == 0) {
            self.navigationController!.navigationBar.topItem!.title = "First"
        }
        else if(self.scrollView.contentOffset.x == self.view.frame.size.width) {
            self.navigationController!.navigationBar.topItem!.title = "Second"
        }
        else if(self.scrollView.contentOffset.x == self.view.frame.size.width*2) {
            self.navigationController!.navigationBar.topItem!.title = "Third"
        }
    }

self.scrollView.contentOffset.x keeps logging null within scrollViewDidEndDragging . Is there a reason why?

将此代码放在scrollViewDidScroll:方法中,不要忘记将self设置为滚动视图的委托。

You should put your code inside scrollViewDidScroll() delegate method, and if you calculations are alright, it will work. Good Luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM