I've been trying to resize the UITextField to fit and stretch out on the entire UINavigationBar but have been unsuccessful. I am aware that this is the simplest problem in the world, but I am oblivious.
It's not the simplest problem in the world. In fact it's rather thorny.
You can't do this using constraints. UINavigationBar
takes responsibility for laying out its subviews. Xcode knows this, so it doesn't let you set constraints on the text field.
The navigation bar asks your text field how big it wants to be by sending it sizeThatFits:
, and provides the maximum allowed size, so one approach is to create a subclass of UITextField
that returns that maximum. This works:
@implementation MyTextField
- (CGSize)sizeThatFits:(CGSize)size {
return size;
}
@end
Another approach is just to make the text field very wide and let the navigation bar shrink it to fit. You need to reset the width on rotation, because the navigation bar won't stretch the text field out again once it's shrunk. Create an outlet in your view controller that connects to the text field, and update the width before layout. This works:
@interface ViewController ()
@property (strong, nonatomic) IBOutlet UITextField *textField;
@end
@implementation ViewController
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
[self widenTextField];
}
- (void)widenTextField {
CGRect frame = self.textField.frame;
frame.size.width = 10000;
self.textField.frame = frame;
}
@end