开发者

Add UITextField to UIToolbar

开发者 https://www.devze.com 2023-03-26 18:08 出处:网络
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 ...

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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号