Maihan Nijat
Maihan Nijat

Reputation: 9355

Why UISearchBar jumps down and first row covered/ overlapped in Swift?

I am adding UISearchBar in UINavigationController as subView but the subView behaves strangely. It hides the section titles for UITableView and it jumps to center vertically when I click on it.

enter image description here enter image description here

And How can I change the background color of UISearchBar to orange? I tried tint color and background color but it didn't work.

var searchController: UISearchController!
var searchResultController: UITableViewController!

override func viewDidLoad() {
    super.viewDidLoad()

    navigationController?.navigationBar.isTranslucent = false

    navigationController?.navigationBar.prefersLargeTitles = true;
    navigationController?.navigationBar.largeTitleTextAttributes = [
        NSAttributedStringKey.foregroundColor : UIColor.white
    ]
    navigationController?.navigationBar.barTintColor = UIColor.orange

    searchController = UISearchController(searchResultsController: searchResultController)

    self.searchController.hidesNavigationBarDuringPresentation = false
    searchController.dimsBackgroundDuringPresentation = false
    self.definesPresentationContext = true

    let searchBar = searchController.searchBar
    searchBar.searchBarStyle = .default
    searchBar.tintColor = UIColor.orange
    searchBar.backgroundColor = UIColor.orange

    view.addSubview(searchBar)
}

Upvotes: 1

Views: 724

Answers (2)

Rishi Chaurasia
Rishi Chaurasia

Reputation: 528

try with below code snippet.

override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        tableView.invalidateIntrinsicContentSize()
    }

Upvotes: 0

Maihan Nijat
Maihan Nijat

Reputation: 9355

I added the below line to hide search bar on the detail ViewController but it was causing the search bar to jump down.

self.definesPresentationContext = true

I removed the line but I had the search bar on detail ViewController and this is how I fixed that.

I passed the search bar variable to the detail view controller and set its property to hidden. I also added the following lines of code to bring the search bar back when a user returns back to the original view.

override func viewWillDisappear(_ animated: Bool) {
    searchBar.isHidden = false
}

The following line of code fix the second problem which hides the first row or section title of the table view.

self.tableView.contentInset = UIEdgeInsetsMake(50,0,0,0);

Upvotes: 3

Related Questions