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

当我加载代码时,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!)

    }    
}

以下是点击前后的视觉效果:

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

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

congine123 回答:为什么我的UISearchBar在点击时会缩小?

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

如果您想独立控制搜索栏的大小,建议您进行searchbar.translatesAutoresizingMaskIntoConstraints = false和/或在viewDidLayoutSubview()中使用searchbar.frame = ...调整搜索栏的大小

本文链接:https://www.f2er.com/2787354.html

大家都在问