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!