When changing UIBarButtonItem title, the transitio

2019-04-20 09:13发布

I have a UIViewController subclass. I give the view controller a rightBarButtonItem in viewDidLoad like this:

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Difficulty"
      style:UIBarButtonItemStylePlain
      target:nil
      action:nil];

When the user presses another button in the view, the title/text of the UIBarButtonItem is changed like this:

self.navigationItem.rightBarButtonItem.title = @"Mellansvår";

It works fine, but when the title is changed, it doesn't look very good. The text jumps around a bit.

I have changed UILabel text at runtime before, and when I change their text is doesn't look like this, but I don't know how to add a UILabel to the navigationItem. I can't do it in Interface Builder because the navigation bar comes from a UINavigationController.

Is there a way to change the title more smoothly?

3条回答
Lonely孤独者°
2楼-- · 2019-04-20 09:44

Instead of setting the title again, you could set the button again with the title and then animate it:

(void)setRightBarButtonItem:(UIBarButtonItem *)item animated:(BOOL)animated
查看更多
爷的心禁止访问
3楼-- · 2019-04-20 09:46

Another solution would be to change the title without animations.

[UIView performWithoutAnimation:^{
    self.navigationItem.rightBarButtonItem.title = @"Mellansvår";
}];
查看更多
贼婆χ
4楼-- · 2019-04-20 09:50

You can skip the animation altogether, if you change the UIBarButtonItem title while it is not attached to the navigationItem, like this:

UIBarButtonItem *tempItem = self.navigationItem.rightBarButtonItem;
self.navigationItem.rightBarButtonItem = nil;
tempItem.title = @"Mellansvår";
self.navigationItem.rightBarButtonItem = tempItem;

The animation will disappear completely, but the visual effect looks way better IMHO.

查看更多
登录 后发表回答