Adding UITextField to UIToolbar does not work

1.6k views Asked by At

I am trying to add a UITextField to UIToolbar on my UINavigationView but it does not appear on the toolbar. The code is very simple. Here's what it looks like:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.toolbarHidden = NO;
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 32)];
    UIBarButtonItem *textFieldItem = [[UIBarButtonItem alloc] initWithCustomView:textField];
    self.toolbarItems = [NSArray arrayWithObjects: textFieldItem, nil];

}

I tried adding other toolbarItems instead, and they all work. For example, the following code works with no problem.

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.toolbarHidden = NO;
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(openCamera:)];
    self.toolbarItems = [NSArray arrayWithObjects: buttonItem, nil];

}

- (void)openCamera:(NSString *)str
{
   // some code..
}

This is the only change I've made to a default generated single view application and I have no idea why it's not working. By the way I am on iOS7. Anyone have an idea what's going on? Thank you!

1

There are 1 answers

0
Benjamin Cheah On

The borderStyle property of UITextField is set to UITextBorderStyleNone by default. That might be why it doesn't appear to be visible. Try this:

urlField.borderStyle = UITextBorderStyleRoundedRect;

On another note, when my view doesn't show up as expected, I usually try to display its border to help me figure out if it's actually on the screen.

view.layer.borderWidth = 1.0f;
view.layer.borderColor = [[UIColor magentaColor] CGColor];