NavigationItem TitleView约束不起作用

时间:2018-10-01 02:22:40

标签: swift uitextfield uinavigationbar swift4.2 titleview

我想使用UITextField创建一个搜索栏。我试图将NavigationItem的TitleView设置为文本字段并设置相应的约束。但是文本字段在导航栏的中心仍然很短。如何使文本框填充整个导航栏?这是我的代码:

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)

它的外观为rn: UIView

2 个答案:

答案 0 :(得分:0)

您应该阅读Apple准则。在iOS11中,您应该将searchBar安装到navigationItem中。尝试使用以下代码:

import UIKit

class ViewController: UIViewController, UISearchControllerDelegate {

var searchController = UISearchController()

override func viewDidLoad() {
    super.viewDidLoad()

    navigationController?.navigationBar.prefersLargeTitles = false
    searchController = UISearchController(searchResultsController: nil)
    searchController.delegate = self

    // Customisation 
    searchController.searchBar.tintColor = .black
    searchController.dimsBackgroundDuringPresentation = false

    navigationItem.searchController = searchController
    navigationItem.hidesSearchBarWhenScrolling = false
}

}

答案 1 :(得分:0)

我解决了我的问题。我没有使用titleView,而是将文本字段放在右侧的barButtonItem中,并将其宽度设置为view.frame.size.width。这给了我一个占据整个导航的文本框。我在这里附加了代码,以防有人也想这样做。

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