问题是您以编程方式创建视图并使用自动调整大小掩码。
https://developer.apple.com/documentation/uikit/uiview/1622572-translatesautoresizingmaskintoco
简单UISearchBar示例:
class ViewController: UIViewController, UISearchBarDelegate {
weak var searchBar: UISearchBar?
override func viewDidLoad() {
super.viewDidLoad()
let searchBar = UISearchBar(frame: .zero)
self.searchBar = searchBar
searchBar.searchBarStyle = .minimal
searchBar.barStyle = .black
searchBar.delegate = self
searchBar.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(searchBar)
NSLayoutConstraint.activate([
searchBar.topAnchor.constraint(equalTo: view.topAnchor, constant: 50.0),
searchBar.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40.0),
view.trailingAnchor.constraint(equalTo: searchBar.trailingAnchor, constant: 40.0),
searchBar.heightAnchor.constraint(equalToConstant: 36.0)
])
}
}