I have implemented a UISearchBar to search through a catalogue of items from an external API. The Search functionality works as expected, however the problem is that every t
Code tested in Swift 3.
Note: When, I, try your code. I was facing the same issue. Somehow, I managed to get around...
class SearchVC: UITableViewController,UISearchBarDelegate,UISearchResultUpdating {
var resultSearchController = UISearchController()
override func viewDidLoad() {
super.viewDidLoad()
configureSearchController()
}
override var prefersStatusBarHidden: Bool {
return true
}
func configureSearchController() {
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = false
controller.hidesNavigationBarDuringPresentation = false
controller.searchBar.searchBarStyle = .default
controller.searchBar.sizeToFit()
controller.searchBar.setShowsCancelButton(false, animated: true)
controller.searchBar.keyboardAppearance = .default
self.tableView.tableHeaderView = controller.searchBar
//controller.searchBar.tintColor = UIColor(patternImage: UIImage(named: "xxxx")!)
// controller.searchBar.setBackgroundImage(UIImage(named: "xxxx"), forBarPosition: UIBarPosition.Top, barMetrics: UIBarMetrics.Default)
// controller.searchBar.backgroundImage = UIImage(named: "xxxx")
// controller.searchBar.setImage(UIImage(named: "search-icon.png"), forSearchBarIcon: UISearchBarIcon.Search, state: UIControlState.Normal)
return controller
})()
for subView in self.resultSearchController.searchBar.subviews
{
for subsubView in subView.subviews
{
if let textField = subsubView as? UITextField
{
textField.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("Search Text", comment: ""), attributes: [NSForegroundColorAttributeName: UIColor.red])
textField.adjustsFontSizeToFitWidth = true
textField.allowsEditingTextAttributes = true
textField.textColor = UIColor.red
textField.layer.borderColor = UIColor.gray.cgColor
textField.layer.cornerRadius = 5
textField.layer.masksToBounds = true
textField.layer.borderWidth = 0.215
}
}
}
}
}
Updated:
func updateSearchResults(for searchController: UISearchController) {}
Output from above code..hope, my answer will fix your problem....
Try to call configureSearchController()
in viewDidLoad
.
And don't forget to call super.viewWillAppear(animated:)
in your viewWillAppear
.
I've made an open source project SearchTableView
self.searchController.searchBar.sizeToFit()
self.tableHeaderView = self.searchController.searchBar
searchTableView.layoutMargins = UIEdgeInsets.zero
definesPresentationContext = true
extendedLayoutIncludesOpaqueBars = true