Add UITextField to UIToolbar
Asked Answered
T

2

18

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.

Trusting answered 7/8, 2011 at 18:40 Comment(0)
L
43

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];
Lib answered 7/8, 2011 at 18:43 Comment(0)
M
2

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!

Milan answered 11/6, 2017 at 9:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.