简体   繁体   中英

Why does my UISearchBar shrink when tapped?

When I load my code, the UISearchBar appears normally. However, after I tap the search field, the search bar shrinks and drops vertically lower. Code:

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!)

    }    
}

Here is a visual before and after tapping:

在此处输入图片说明

在此处输入图片说明

UIkit will resize the searchcontroller's view on layoutSubviews() which will reset your frame.

If you want to control the size of the search bar independently, I'll suggest you make searchbar.translatesAutoresizingMaskIntoConstraints = false and/or in viewDidLayoutSubview() resize your searchbar with searchbar.frame = ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM