Add UITextField to title view of navigation item

2020-08-17 07:43发布

问题:

How do you add a text field to the title view of a navigation item and have it sized correctly?

It works fine if I do this with a search bar like this but I don't know how to get a text field to size itself in the same way as a search bar.

myViewController.navigationItem.titleView = [UISearchBar new];

回答1:

As my comment suggested, try the following, which seems to me is what you're after.

UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, self.navigationController.navigationBar.frame.size.width, 21.0)];

self.navigationItem.titleView = textField;

[textField becomeFirstResponder];


回答2:

Class: ViewController: UISearchBarDelegate {

let searchController = UISearchController(searchResultsController: nil)
navigationItem.searchController = searchController
navigationItem.searchController?.searchBar.delegate = self
navigationItem.searchController?.obscuresBackgroundDuringPresentation = false
navigationItem.searchController?.hidesNavigationBarDuringPresentation = false
navigationItem.searchController?.searchBar.placeholder = "Enter text here..."