Reputation: 155
I have a button in my navigation bar which, when pressed, calls a function (showAddItemtextField) that shows a text field as a titleView in the navigation bar.
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "+", style: .plain, target: self, action: #selector(showAddItemTextField))
That much is ok so far, and I can type text into the text field (I know because when I tap on the text field the placeholder text disappears, and when I type I get autocomplete suggestions), but the text I type is otherwise invisible.
Here's my code so far:
// Show text field upon add button press
lazy var addItemTextField: UITextField = {
let textField = UITextField()
textField.placeholder = "Add a new item..."
return textField
}()
func showAddItemTextField() {
self.navigationItem.titleView = addItemTextField
}
I'm not sure if the issue is because the new text field, as a navigationItem.titleView, goes on top of what is usually there (navigationItem.title). Do I have to hide navigationItem.title when the text field is present? Or is a different problem?
I should also add that the onscreen keyboard does not appear when I tap on the text field.
Upvotes: 0
Views: 2282
Reputation: 534977
The problem is that your text field has no size. You failed to give it a size when you created it, when you said:
let textField = UITextField()
Then you compounded the problem by the unnecessary textField.translatesAutoresizingMaskIntoConstraints
line.
This works fine for me:
let tf = UITextField(frame:CGRect(origin:.zero, size:CGSize(width:100, height:28)))
tf.borderStyle = .bezel
self.navigationItem.titleView = tf
I'm not saying that that's the size / look you want, but it makes a visible text field you can type into.
Upvotes: 1