Reputation: 945
Is there a way to limit the frame size of a UITextField
after calling setText? All other questions seem to pertain to adjusting the size based on the string after user editing, or limiting the size of the string itself while editing.
The UITextField is initialized from IB, then in viewDidLoad I call setText. The UITextField
is a UINavigationItem
on a UINavigationBar
.
- (void)viewDidLoad {
[super viewDidLoad];
NSString *theURL = [NSString stringWithFormat:@"http://stackoverflow.com/questions/ask/ThisIsABogusURLForExamplePurposes.htm"];
[_addressBar setText:theURL];
}
In this case I do need the user to be able to edit the string but it's also set in code the first time the view is presented. In IB I have set the width to the desired maximum width and if I populate the UITextField
with a small string it remains that size. However, calling setText with any string that results in text appearing beyond the width of the field, causes it to stretch the UITextField
width to the full length of the UINavigationBar
. I have tried to programmatically set the frame size of the field after setText is called but it seems to have no effect.
Thanks for any help!
Upvotes: 1
Views: 615
Reputation: 2278
I had a similar problem and I have not been able to solve it using interface builder. What I did is add the addressbar with a fixed size programmatically to a UIView of a certain size. This UIView is then set as the titleView of the navigation item.
This left-aligns the textfield, and will recalculate its placement again when you rotate the device (thats why I overrided viewWillLayoutSubviews).
- (void)viewWillLayoutSubviews
{
NSString *theURL = [NSString stringWithFormat:@"http://stackoverflow.com/questions/ask/thisIsABogusURLForExamplePurposes.htm"];
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.navigationController.navigationBar.frame.size.width, 30.0)];
UITextField *addressBar = [[UITextField alloc] initWithFrame:CGRectMake(0.0, 0.0, 200.0, 30.0)];
[addressBar setBorderStyle:UITextBorderStyleRoundedRect];
[addressBar setText:theURL];
[containerView addSubview:addressBar];
[[self navigationItem] setTitleView:containerView];
}
Upvotes: 1