Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide Navigation Controller Search Bar & opened Large Title programmatically

I have a tableView. I set the all settings about searchController ( Search Bar in Large Navigation Bar ) - ( open / close when scroll tableview ). I implemented rightBarButtonItem which name is 'Close' . I want to hide/close tableView and Search Bar with programmatically. I can hide tableView but not SearchBar.

When I do isHidden for SearchBar , The Large Navigation Bar doesnt shrink to normal size.

Pic 1. Opened search bar with scroll down.

enter image description here

Pic 2. Not Hidden Large Navigation Bar with programmatically ( searchar.isHidden not implemented here )

enter image description here

Thanks in advance.

I tried this before but not run

tableView.setContentOffset(.zero, animated: false)
navigationController?.navigationBar.prefersLargeTitles = false
like image 345
Ali Ihsan URAL Avatar asked Oct 07 '18 14:10

Ali Ihsan URAL


2 Answers

I tried to find a proper way to hide search bar, but I didn't find. But I found a workaround to hide your search bar which is change content offset your table view.

You may try this function to hide your table view and search bar.

func hide() {
    tableView.isHidden = true
    let point = tableView.contentOffset
    let searchBarFrame = self.navigationItem.searchController?.searchBar.frame
    let newPoint = CGPoint(x: point.x, y: point.y + searchBarFrame!.height)
    tableView.setContentOffset(newPoint, animated: true)
}
like image 176
Alperk Avatar answered Dec 08 '22 06:12

Alperk


Just try this:

 navigationItem.searchController = nil

This is all my test code:

@IBOutlet weak var tableView: UITableView!

@IBOutlet weak var leftBarButtonItem: UIBarButtonItem!

var isHidden = false

var searchController: UISearchController {

    let search = UISearchController(searchResultsController: nil)

    search.searchBar.placeholder = "hello world"

    search.obscuresBackgroundDuringPresentation = false

    return search
}


override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationItem.title = "Test"

    tableView.delegate = self

    tableView.dataSource = self

    showSearchController()
}

@IBAction func isHiddenAction(_ sender: UIBarButtonItem) {
    isHidden = !isHidden

    self.tableView.isHidden = isHidden

    if isHidden {
        leftBarButtonItem.title = "Show"
        hiddenSearchController()

    } else {
        leftBarButtonItem.title = "Hidden"
        showSearchController()
    }
}

func hiddenSearchController() {
    navigationItem.searchController = nil
}

func showSearchController() {

    navigationItem.searchController = searchController

    navigationItem.hidesSearchBarWhenScrolling = true

    definesPresentationContext = true
}

screenShots

like image 31
UninhibitedSoul Avatar answered Dec 08 '22 04:12

UninhibitedSoul