swift


No found anything when use searchbar in swift 3


I have a little problem. I can search in a array via searchbar. But when I search a city not in my array, doesn't change anything. I want to show error message this case. For example 'Not found any city'
My code is below:
var cities = [String]()
var citiesFiltered = [String]()
var searchBarActive:Bool = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
cities = ["Abu Dabi","Amman","Berlin","Catarman","Dortmund"]
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if(searchBarActive){
return citiesFiltered.count
}
return cities.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
if(searchBarActive){
cell.textLabel?.text = citiesFiltered[indexPath.row]
}else{
cell.textLabel?.text = cities[indexPath.row]
}
return cell
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBarActive = true
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchBarActive = false
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBarActive = false
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBarActive = false
}
func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
searchBarActive = false
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
citiesFiltered = cities.filter({ (text) -> Bool in
let txt : NSString = text as NSString
let range = txt.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
return range.location != NSNotFound
})
if(citiesFiltered.count == 0){
searchBarActive = false
}else{
searchBarActive = true
}
self.tableView.reloadData()
}
//Try with this changes.
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if(searchBarActive && citiesFiltered.count == 0){
return 1
}
else if searchBarActive {
return citiesFiltered.count
}
return cities.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
if(searchBarActive && citiesFiltered.count == 0){
cell.textLabel?.text = "Not found any city"
}
else if searchBarActive {
cell.textLabel?.text = citiesFiltered[indexPath.row]
}
else{
cell.textLabel?.text = cities[indexPath.row]
}
return cell
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
citiesFiltered = cities.filter({ (text) -> Bool in
let txt : NSString = text as NSString
let range = txt.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
return range.location != NSNotFound
})
self.tableView.reloadData()
}
The problem is here
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
citiesFiltered = cities.filter({ (text) -> Bool in
let txt : NSString = text as NSString
let range = txt.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
return range.location != NSNotFound
})
if(citiesFiltered.count == 0){
searchBarActive = false
}else{
searchBarActive = true
}
self.tableView.reloadData()
}
You are setting the bar as inactive, hence displaying the unfiltered list, when the filtered array is empty.
By removing
if(citiesFiltered.count == 0){
searchBarActive = false
}else{
searchBarActive = true
}
You'll get an empty table when searching for something that is not on the list.

Related Links

Going from one ViewController to another ViewController and updating
Setting Text View to be Int rather than String? Swift
Why I am getting ERROR: Type 'Any' has no subscript members when trying to use ELCimagepickercontroller
UIActivityViewController using multiple arrays
how to call Swift closure callback
Realm Notification is not triggered when NSPredicate changes
Parse can't retrieve CurrentUser's array objects
Use of unresolved type MutableProperty
How to have label text change to message after user types in textfield?
RxSwift/RxCocoa: Code Completion barely working
Completion block never called at end of SKAction sequence of groups
What is the best way to zoom and deplace nodes?
How to handle PUT HTTP request in Vapor?
Getting HTTP headers with URLSessionDownloadDelegate
Core location returning 0 as altitude
SKWarpGeometry on SKLabelNode as child of SKEffectNode flips label upside-down

Categories

HOME
spring
visual-studio-2015
jar
wsdl
facebook-graph-api
steam
chaiscript
appmaker
flyway
java-home
tumblr
sequelize.js
apiconnect
sudo
eval
goutte
metronic
public-key-encryption
symfony-forms
equalizer
apache-karaf
redux-observable
jive
google-maps-android-api-2
cruisecontrol.net
onsen-ui
spring-ws
binutils
shopping-cart
python-textprocessing
java-ee-7
metadata-extractor
dpi
cell-array
red-black-tree
skygear
receipt
npm-publish
jquery-multidatespicker
alchemy.js
microdata
pytest-django
finite-element-analysis
bids
recycle-bin
nstouchbar
ruby-on-rails-2
tofixed
search-box
laravel-query-builder
sql-import-wizard
software-product-lines
visible
spring-lemon
fortran90
approval-tests
mptcp
playscape
on-duplicate-key
graphical-logo
coypu
adobe-indesign
ejabberd-saas
moai
suffix-array
proxies
spdy
cppdepend
dbsetup
dvcs
openkinect
windows-mobile-6
goinstant
trimming
ruboto
mstsc
dwolla
gdataxml
dropdownlistfor
returnurl
usn
ubuntu-11.04
hinstance
emacs23
selectonemenu
electronic-signature
coff
executable-format
gtk2hs
exitstatus
querypath
delegatecommand
graph-layout

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App