In a UIToolbar
, I have added a UITextField
to the middle of the bar (which gets added as a UIBarButtonItem
) with another UIBarButtonItem
(Action button) next to it. I added flexible space bar button items at the very left and very right. It looks great on portrait, but when I rotate to landscape it centers them and looks ok, but I need the text field to get stretched to fill the width and push the last button clear to the right - exactly like it does in Messages - on iPhone and iPad.
I thought Auto Layout would do the trick but Apple states you cannot create constraints for UIBarButtonItem
s. And indeed when I select any of the bar buttons or the text field it will not allow creating any constraints.
Could you please let me know how to accomplish this? Thanks!
EDIT: I've tried a few other combinations with fixed/flexible spaces. When I don't add any, the text field and share button are pushed over to the left:
If instead I do fixed spaces, it looks the exact same as above with 0 widths, or if I set a width then it obviously will push them over. That last space on the far right has no effect - it's not fixed against the far right side so it goes off the screen.
I tried a fixed space on the left and a flexible on the right, with the middle one fixed (or no middle one), and it looks like the screenshot above. I then changed the middle one to flexible and it turned out like this:
If I change the first to flexible, none in the middle (or if I add a fixed one), and flxed on the right, it is moved over to the right:
If the first is flexible, middle is flexible, and right is fixed, this is how it looks:
In all cases the width of the text field remains the same static value as it was originally set up in the storyboard. I think the problem is that when you set the width by dragging the frame, there are no blue guidelines to snap to so it will always remain that same width.
Did I miss any combination of spaces? If I cannot implement the desired behavior in the interface builder, how would one accomplish this in code?
To obtain a horizontally stretching text field, I had to manually set its frame
in viewWillAppear
and also when the orientation changes - I used viewWillTransitionToSize:withTransitionCoordinator:
:
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> __nonnull context) {
self.textField.frame = CGRectMake(0, 0, self.navigationController.navigationBar.frame.size.width - self.actionButton.width - 55, self.inputTextField.frame.size.height);
} completion:^(id<UIViewControllerTransitionCoordinatorContext> __nonnull context) {
}];
Previous solution (no longer works for me in latest OSes):
Add this in viewDidLoad
:
self.textField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With