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

Date Picker Only Works After Clicking out of Text Field
optional variable in class definition
Swift UILabel word wrap for Chinese?
Not able to get results for spotlight search for user tags with NSMetadataquery and kMDItemUserTags
swift: how to generate arm7 or arm64 from the command line
Dictionary<string,Dictionary> in swift 3.0 giving nil when tried to add a dict [duplicate]
Unwrap optional inside switch case [duplicate]
why is my xib button not aligning with my simulator keyboard screen?
Xcode swift login with Facebook SDK app not loading
Get next value on a map?
Swift Detecting a Change in a Textfield from a .xib file
Firebase retrieve data multiple filters [duplicate]
Swift3 setting constraints relative to parent view of parent view
Using a string parameter to describe class property
Generic dictionary extension error - ambiguous reference to subscript
Scrolling locks updates to UIButton [duplicate]

Categories

HOME
sql-server-2008
ajax
udp
mql4
vhdl
websphere
winapi
windows-7
google-contacts
agile
puppet
aem
search-engine
checksum
terrain
dataframe
simpy
pygame
structuremap
diagram
oclint
google-shopping
lagom
image-recognition
data-synchronization
gwtp
store
zend-framework-mvc
pycrypto
shippo
url.action
iis-10
auditing
java-ee-7
pipelinedb
guile
widevine
chrome-native-messaging
devforce
pari
smart-mobile-studio
ksoap
code-composer
homekit
fastq
python-idle
rollback
chrome-remote-desktop
jszip
onresume
windows-azure-pack
activeweb
mailcatcher
post-processing
qt-linguist
void
sonarqube5.3
app.xaml
ubercart
google-earth-plugin
cg
log4cplus
java-collections-api
facebook-wall
csplit
korma
delphi-xe3
pyjade
nsmatrix
gridworld
backbone-relational
nuspec
fraud-prevention
reporting-tools
marmalade-edk
cosm
mpmovieplayer
z-machine
text-services-framework
ou
nemerle
datacontract
getresource
osx-leopard
yajl
boost-date-time
asp.net-mvc-controller
revision
visual-studio-dbpro

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