Add UITextField to UIToolbar

user523234 picture user523234 · Aug 7, 2011 · Viewed 12.6k times · Source

I tried this to add UITextField to a UIToolbar but got a run-time error with reason as: [UITextField view]: unrecognized selector sent to instance ...

[toolbar setItems:[NSArray arrayWithObjects:textField, nil]];

toolbar is an instance of UIToolbar and textField is an instance of UITextField.

Answer

omz picture omz · Aug 7, 2011

The items of a UIToolbar have to be of type UIBarButtonItem. Use initWithCustomView: to create a toolbar item that contains your text field.

UIBarButtonItem *textFieldItem = [[UIBarButtonItem alloc] initWithCustomView:textField];
toolbar.items = @[textFieldItem];