Reputation: 1995
I'm trying to do a simple thing: add a UIBarButtonItem on the right side of my navBar. Seemed like an easy task:
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:@"Button" style:UIBarButtonItemStylePlain target:self action:@selector(buttonTapped)];
[self.navigationItem setRightBarButtonItem:button];
But when that method gets called, a strange thing happens: the button slides all the way over from the left side of the bar.
Rather than just appearing on the right side, the right bar button appears on the far left, quickly slides across the entire navbar (under the title in the center), and slows to a stop in the right-side position. From there on, it works exactly as expected.
As simple as it sounds, I can't get the right bar button to stop sliding in like this. I've tried adding animated:NO
and animated:YES
to the setRightBarButtonItem:
method, with no effect either way. It happens whether or not there is a UIBarButtonItem on the left side. I've tried using setRightBarButtonItems:@[button]
, but the slide animation is unchanged.
Does anyone know how I can add a simple UIBarButtonItem to the right side of my navBar without it sliding in from the side?
Upvotes: 2
Views: 389
Reputation: 51
I got the same issue, in my case I was adding a 'hide keyboard' button on the rightBarButtonItem. I did this in the selector for UIKeyboardWillShow notification and maybe this selector is called from within the the animation block for showing the keyboard. I just disabled the animations while adding the button.
UIView.setAnimationsEnabled(false)
self.navigationItem.setRightBarButton(hideKeyboardButton, animated: true)
UIView.setAnimationsEnabled(true)
Upvotes: 0
Reputation: 48514
You have somehow embedded setRightBarButtonItem
in an animation of sorts.
If you look very closely, you will notice that it does not actually goes from left to right per say, but from (0, 0) with a size of (0, 0) to its final resting location and dimensions. The navigationItem
is held hostage within an animation.
To convince oneself, you can run this simple snippet:
func buttonTapped() {
UIView.animateWithDuration(5) { () -> Void in
let button = UIBarButtonItem(title: "Button",
style: .Plain,
target: self,
action: "buttonTapped")
self.navigationItem .setRightBarButtonItem(button, animated: false)
}
}
Demo
Upvotes: 1