为什么我的 UISearchBar 在点击时会缩小?

Why does my UISearchBar shrink when tapped?

当我加载代码时,UISearchBar 正常显示。但是,在我点击搜索字段后,搜索栏会缩小并垂直下降。代码:

class MainViewController: UIViewController, UISearchBarDelegate {

    var searchBarController: UISearchController?
    var tableViewController: UITableViewController?
    var searchBar: UISearchBar?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .blue

        let tableViewController = UITableViewController(style: .plain)
        let searchBarController = UISearchController(searchResultsController: tableViewController)

        self.searchBarController = searchBarController
        self.tableViewController = tableViewController

        self.searchBar = self.searchBarController?.searchBar
        self.searchBar?.frame = CGRect(x: 0, y: 50, width: self.view.frame.size.width, height: 75)
        self.searchBar?.searchBarStyle = .prominent
        self.view.addSubview(self.searchBar!)

    }    
}

这是点击前后的视觉效果:

UIkit 将在 layoutSubviews() 上调整搜索控制器视图的大小,这将重置您的框架。

如果您想独立控制搜索栏的大小,我建议您在 viewDidLayoutSubview() 中将 searchbar.translatesAutoresizingMaskIntoConstraints = false and/or 调整为 searchbar.frame = ...