Search code examples
swiftuitextfielduinavigationbarswift4.2titleview

NavigationItem TitleView constraint not working


I want to create a search bar using UITextField. I tried to set NavigationItem's TitleView to the textfield and set corresponding constraints. But the textfield remain very short in the center of the navigation bar. How to make the textfield fill the whole navigation bar? Here is my code:

cancelbtn = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(CourseTableViewController.searchCancelled))
self.navigationItem.leftBarButtonItem = cancelbtn

let searchField = UITextField()
searchField.translatesAutoresizingMaskIntoConstraints = false
searchField.borderStyle = .roundedRect
self.navigationItem.titleView = searchField
self.navigationItem.titleView!.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: cancelbtn.width)
self.navigationItem.titleView!.widthAnchor.constraint(equalToConstant: view.frame.size.width - cancelbtn.width)

And is how it looks rn: UIView


Solution

  • I solved my problem. Instead of using the titleView, I put the textfield in the right barButtonItem and set its width to view.frame.size.width. This gives me a textfield that occupy the whole navigation. I attached the code here incase someone also wants to do it.

    searchBar = UISearchBar()
    searchBar.showsCancelButton = false
    searchBar.placeholder = "Course name"
    searchBar.delegate = self
    cancelbtn = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(CourseTableViewController.searchCancelled))
    self.navigationItem.leftBarButtonItem = cancelbtn
    
    searchTextField = UITextField()
    searchTextField.borderStyle = .roundedRect
    searchTextField.widthAnchor.constraint(equalToConstant: view.frame.size.width - cancelbtn.width)
    searchTextField.translatesAutoresizingMaskIntoConstraints = false
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: searchTextField)
    self.navigationItem.rightBarButtonItem?.width = view.frame.size.width