UISeachController Delegate methods not called, searchbar can't become first responder - swift

I'm having some difficulty getting the searchbar in my searchcontroller to become firstResponder. I've noticed the delegate methods are not being called, but the searchbar works as intended when I'm typing to filter a list of users.
Definition of searchcontroller:
lazy var searchController: UISearchController = {
let searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search"
return searchController
}()
Setting it up:
private func setupSearchController() {
self.navigationItem.searchController = searchController
searchController.definesPresentationContext = true
searchController.delegate = self
searchController.isActive = true
searchController.searchBar.delegate = self
searchController.searchBar.becomeFirstResponder()
}
I tried this suggestion from another SO question but the delegate method isn't being called:
func didPresentSearchController(searchController: UISearchController) {
UIView.animate(withDuration: 0.1, animations: { () -> Void in }) { (completed) -> Void in
searchController.searchBar.becomeFirstResponder()
}
}

The problem is you are trying to access UI element(searchbarcontroller) before UI is completely loaded.
This can be done in 2 ways
Use main queue to show keypad
private func setupSearchController() {
self.navigationItem.searchController = searchController
searchController.definesPresentationContext = true
searchController.delegate = self
searchController.isActive = true
searchController.searchBar.delegate = self
DispatchQueue.main.async {
self.searchController.searchBar.becomeFirstResponder()
}
}
With this approach keypad will be only show at one time in viewDidLoad
Show keypad in viewDidAppear
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
DispatchQueue.main.async {
self.searchController.searchBar.becomeFirstResponder()
}
}
With this approach keypad will be always shown whenever screen appears.

Related

Swift: deallocate modally presented view controller

I have a modally presented SearchviewController that contains a UISearchController.
When swiping down it gets deallocated, but only if the searchControllers searchBar is not in editing mode. Only if I press its cancel button in advance, it gets deallocated.
How can I make sure it gets deallocated, even when in editing mode? There are definitely no strong self references within any closures...
Presenting ViewController:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
addButton()
}
func addButton() {
let mediumConfiguration = UIImage.SymbolConfiguration(scale: .large)
var checkButtonImage = UIImage(systemName: "plus", withConfiguration: mediumConfiguration)
checkButtonImage = checkButtonImage?.withTintColor(.label)
let button = UIButton(type: .contactAdd)
button.addTarget(self, action: #selector(onAddViewControllerButtonClicked(sender:)), for: .touchUpInside)
view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
}
#objc func onAddViewControllerButtonClicked(sender: UIButton) {
let viewController = SearchViewController()
viewController.view.backgroundColor = .secondarySystemBackground
let navigationController = UINavigationController()
navigationController.viewControllers = [viewController]
self.present(navigationController, animated: true)
}
}
Presented ViewController:
class SearchViewController: UIViewController, UISearchBarDelegate, UISearchResultsUpdating {
override func viewDidLoad() {
super.viewDidLoad()
configureSearchController()
}
var searchController: UISearchController?
func configureSearchController() {
//search
searchController = UISearchController(searchResultsController: nil)
searchController?.searchResultsUpdater = self
searchController?.searchBar.delegate = self
searchController?.hidesNavigationBarDuringPresentation = false
searchController?.searchBar.searchBarStyle = .minimal
searchController?.searchBar.keyboardType = .webSearch
self.navigationItem.searchController?.searchBar.backgroundColor = .clear
self.navigationItem.searchController = searchController
self.navigationItem.hidesSearchBarWhenScrolling = false
self.definesPresentationContext = true
self.navigationItem.searchController = searchController
}
func updateSearchResults(for searchController: UISearchController) {
return
}
//check deallocation
deinit { print("\(NSStringFromClass(type(of: self))): deallocated") }
}
Can you help with that?
Thank you in advance!
Adding
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.navigationItem.searchController = nil
}
to SearchViewController fixes the problem for me, but admittedly I have no idea as to why this is necessary.

Swift - UISearchController Does Not Activate - No Cursor - No Keyboard

I have a UICollectionView with a header view inside of it and a UISearchController in the title of the navigation bar. This code has worked for other views yet does not work for this UICollectionView. I wanted to throw this out to the SO community to see if they can help me solve this problem.
class ViewBusinessProfile: UICollectionViewController, UICollectionViewDelegateFlowLayout, CLLocationManagerDelegate, UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {
#IBOutlet var collectionViews: UICollectionView!
var searchController : UISearchController!
override func viewDidLoad() {
super.viewDidLoad()
self.searchController = UISearchController(searchResultsController: nil)
self.searchController.searchResultsUpdater = self
self.searchController.delegate = self
self.searchController.searchBar.delegate = self
self.searchController.hidesNavigationBarDuringPresentation = false
self.searchController.dimsBackgroundDuringPresentation = true
self.searchController.obscuresBackgroundDuringPresentation = false
self.searchController.searchBar.placeholder = "search products..."
//self.searchController.automaticallyShowsCancelButton = false
self.searchController.definesPresentationContext = true
searchController.searchBar.becomeFirstResponder()
navigationItem.titleView = searchController.searchBar
collectionViews.dataSource = self
collectionViews.delegate = self
}
func updateSearchResults(for searchController: UISearchController) {
}
What can I do as far as debugging or anything to try to track down this problem? I have re-created the view in a new UICollectionView and the same problem occurs. The SearchBar is visible but not active to touch yet Back button works on the navigation bar.
These three views all have UISearchControllers on them and I segue between them. The one all the way on the right is where this problem is occurring. The same UISearchController code is used on the left two views and its works perfectly.
Based on what I saw in this related solution, I came up with this code:
import UIKit
class SecondViewController: UIViewController, UISearchControllerDelegate, UISearchBarDelegate {
var searchController : UISearchController!
override func viewDidLoad() {
super.viewDidLoad()
addNavigationBarItems()
}
func addNavigationBarItems() {
self.searchController = searchControllerWith(searchResultsController: nil)
navigationItem.titleView = self.searchController.searchBar
self.definesPresentationContext = true
}
func searchControllerWith(searchResultsController: UIViewController?) -> UISearchController {
let searchController = UISearchController(searchResultsController: searchResultsController)
searchController.delegate = self
// searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.hidesNavigationBarDuringPresentation = false
// dimsBackgroundDuringPresentation is deprecated as of iOS 12.0
searchController.dimsBackgroundDuringPresentation = true
searchController.searchBar.searchBarStyle = .prominent
searchController.searchBar.backgroundImage = UIImage()
searchController.searchBar.barTintColor = UIColor(red: 10/255, green: 150/255, blue: 255/255, alpha: 1) //rgb(10, green: 150, blue: 255)
return searchController
}
func updateSearchResults(for searchController: UISearchController) {
}
}
This assumes a navigation bar already exists in the parent view controller (i.e. you don't have to create a new NavigationBar), and results should come out looking like this:

How to redraw NavigationBar to show SearchController on button press?

I am using a button in my navigationItem.title, which when pressed, I would like to display the navigationItem.searchController.
When cancel is pressed on the search bar, I would like to dismiss the search controller, and redraw the navigation bar.
var universalSearchController = UISearchController(searchResultsController: nil)
override func viewWillAppear(_ animated: Bool) {
// Set search delegate and who will be updating the results
universalSearchController.searchBar.delegate = self
universalSearchController.searchResultsUpdater = self
universalSearchController.delegate = self
definesPresentationContext = true
titleButton.addTarget(self, action: #selector(titleButtonTapped), for: .touchUpInside)
}
Basically everything I have tried is all in here:
#objc func titleButtonTapped() {
// Set the searchController
navigationItem.searchController = universalSearchController
// Below are attempts at redrawing the navigation bar
universalSearchController.searchBar.becomeFirstResponder()
universalSearchController.searchBar.isHidden = false
// Try to refresh by showing/hiding
self.navigationController?.isNavigationBarHidden = true
self.navigationController?.isNavigationBarHidden = false
universalSearchController.view.setNeedsLayout()
universalSearchController.view.layoutIfNeeded()
universalSearchController.view.setNeedsDisplay()
universalSearchController.view.reloadInputViews()
view.setNeedsDisplay()
view.setNeedsLayout()
view.layoutIfNeeded()
view.reloadInputViews()
navigationController!.navigationBar.setNeedsDisplay()
navigationController!.navigationBar.setNeedsLayout()
navigationController!.navigationBar.layoutIfNeeded()
navigationController!.navigationBar.reloadInputViews()
navigationController!.view.setNeedsDisplay()
navigationController!.view.setNeedsLayout()
navigationController!.view.layoutIfNeeded()
navigationController!.view.reloadInputViews()
}
For hiding the searchController:
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
// Get rid of the searchController
navigationItem.searchController = nil
universalSearchController.searchBar.isHidden = true
universalSearchController.searchBar.resignFirstResponder()
// Try to refresh by showing/hiding
self.navigationController?.isNavigationBarHidden = true
self.navigationController?.isNavigationBarHidden = false
navigationController?.navigationBar.backgroundColor = .red
universalSearchController.view.setNeedsLayout()
universalSearchController.view.layoutIfNeeded()
universalSearchController.view.setNeedsDisplay()
universalSearchController.view.reloadInputViews()
view.setNeedsDisplay()
view.setNeedsLayout()
view.layoutIfNeeded()
view.reloadInputViews()
navigationController!.navigationBar.setNeedsDisplay()
navigationController!.navigationBar.setNeedsLayout()
navigationController!.navigationBar.layoutIfNeeded()
navigationController!.navigationBar.reloadInputViews()
}
The weird thing is that if I present a view over my current table view, and then dismiss it, the navigation bar is there.

UISearchController - Black Rectangle

I'm implementing a simple tableViewController with UISearchcontroller.
The problem is that every time that I press the search field then a black rectangle appear right after the keyboard shows up.
I also tried to use definesPresentationContext and searchBarStyle but it keep showing the rectangle. On the other hand, it looks like doesn't happen in the simulator since there is no keyboard.
Update: Below some photos.
ViewController:
class ListGlobalViewController: UITableViewController, StoryboardSceneBased, ViewModelBased {
static var sceneStoryboard: UIStoryboard = UIStoryboard(name: "DataSelectorViewController", bundle: Bundle.main)
// --------------------
// MARK: - Properties
// --------------------
var viewModel: ListGlobalViewModel!
private let disposeBag = DisposeBag()
private let searchController: UISearchController = {
let searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.searchBarStyle = .minimal
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = true
return searchController
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
configure(with: viewModel)
navigationItem.largeTitleDisplayMode = .automatic
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.searchController.isActive = false
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
// --------------------
// MARK: - Functions
// --------------------
func configure(with viewModel: ListGlobalViewModel) {
self.tableView.delegate = nil
self.tableView.dataSource = nil
viewModel.outputs.listDataObservable.bind(to: self.tableView.rx.items(cellIdentifier: "listGlobalCell", cellType: ListGlobalCell.self)) { (index, model, cell) in
cell.model = model
}.disposed(by: disposeBag)
searchController.searchBar.rx.text.filterNil().throttle(1, scheduler: MainScheduler.instance).distinctUntilChanged().subscribe(viewModel.inputs.searchBarObservable).disposed(by: disposeBag)
}
}
Navigation Default Values:
let controller = UINavigationController()
controller.navigationBar.isTranslucent = false
controller.navigationBar.prefersLargeTitles = true
controller.definesPresentationContext = true
controller.navigationBar.titleTextAttributes = [ NSAttributedString.Key.font: UIFont.bold(size: 24), NSAttributedString.Key.foregroundColor: UIColor.black ]
if #available(iOS 11, *) {
controller.navigationBar.largeTitleTextAttributes = [ NSAttributedString.Key.font: UIFont.bold(size: 33), NSAttributedString.Key.foregroundColor: UIColor.black ]
}
return controller
Pictures:
Bugged
Use UITextField instead if UISearchBar. You can give any design to uitextfield. UISearch bar has limited designable attributes. Also you can reach any search function with textfield.

Search Bar Doesn't Appear When View loads - iOS

I'm having a problem when one of my views initiated. I'm trying to get the search bar to show up when the view is initiated, but it shows up when I start scrolling down.
This shows up when I click on it:
and I'm trying to get this to show up when the view is initiated, which currently only shows up only when I start scrolling:
This is the code I have to set the search controller up so far:
searchController.searchBar.scopeButtonTitles = ["Posts", "Users"]
searchController.searchBar.delegate = self
navigationController?.navigationItem.searchController = searchController
navigationController?.navigationItem.searchController?.searchBar.isHidden = false
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search"
searchController.searchBar.isHidden = false
searchController.searchBar.showsScopeBar = true
// searchController.hidesNavigationBarDuringPresentation = false
self.navigationController?.setNavigationBarHidden(false, animated: true)
navigationItem.searchController = searchController
// navigationController?.navigationItem.hidesSearchBarWhenScrolling = false
definesPresentationContext = true
I've tried lots of different ways to get the search bar to appear when clicked on but I haven't been successful. Any ideas?
You need to add this line:
navigationItem.hidesSearchBarWhenScrolling = false
And if you wan't to show if from the beginning and hide it when scrolling then you need to do this:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if #available(iOS 11.0, *) {
navigationItem.hidesSearchBarWhenScrolling = false
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if #available(iOS 11.0, *) {
navigationItem.hidesSearchBarWhenScrolling = true
}
}