Add UITextField to UIToolbar
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:te开发者_StackOverflowxtField, nil]];
toolbar is an instance of UIToolbar and textField is an instance of UITextField.
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];
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!
精彩评论