Reputation: 14834
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.
Upvotes: 18
Views: 13380
Reputation: 2468
omz's answer above still answered my question in 2017 but here is an update to iOS 10 and Swift 3. I am going to create a UIToolbar
, which has a UITextField
and .flexibleSpace
on its left and right sides to center the text field within the toolbar.
let toolbar = UIToolbar()
let flexibleBarButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
let textfield = UITextField()
let textfieldBarButton = UIBarButtonItem.init(customView: textfield)
// UIToolbar expects an array of UIBarButtonItems:
toolbar.items = [flexibleBarButton, textfieldBarButton, flexibleBarButton]
view.addSubview(toolbar)
You can of course shorten the above code and add the UIToolbar
's frame etc. but the above should be a more "legible" example of specifically adding a UITextField
as a UIBarButtonItem
.
I hope this helps!
Upvotes: 2
Reputation: 53551
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];
Upvotes: 43