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

Cannot load default library in Metal using Swift
Issue with completion handlers in Swift
Custom UITableViewCell UIButton setTitle not working as planned
FloatingPoint in place of Float/CGFloat?
'Incorrect argument label' when method overloading in Swift
Understanding the “last cached state” of NSManagedObject
Swift Perfect does not load image or css
Generic class with reference to itself
Index of enum element in for-case pattern matching
Get Size of UImage when in UIImageView when ContentMode = AspectFill
Last index of Collection as a new Image for Annotation
Cannot convert value of type Int to expected argument type IndexPath (Core Data)?
Disable automatic convenience initializer inheritance in Swift
Getting crash while adding a new node in firebase using swift 3
Protocol function implementation without actually conforming to a protocol
Life cycle when using a struct or class (?) to encapsulate all Firebase operations

Categories

HOME
makefile
dotnetrdf
caching
sas
drupal-7
nuxeo
wxwidgets
bibtex
chaiscript
laravel-4
bro
i2c
onenote-api
pjsip
typeahead
scala-native
apache-karaf
factor-analysis
jogl
tweets
google-maps-android-api-2
autolayout
countif
hhvm
binutils
sumo
jenkins-job-dsl
osmdroid
owl-api
superscript
roundcube
jackson-dataformat-csv
postgresql-9.2
idl
threshold
color-scheme
xamarin.uitest
issue-tracking
deepstream.io
wsadmin
crop
automator
vcf
walmart-electrode
pinvoke
jenkins-jira-trigger
struts-layout
photon-controller
react-native-fbsdk
pycurl
date-range
lotus
gulp-typescript
objloader
software-product-lines
cron-task
json-schema-validator
gameanalytics
uiprogressview
spatial-query
remoteapp
elastix
asp.net-mvc-partialview
post-processing
usb-drive
flexjson
cpan
ibmsbt
livechat
getimagedata
bullet
argument-passing
initialization-vector
edit-in-place
internal
pyjade
layered
jqmobi
ng-pattern
symphony-cms
qtgui
qt4.6
arbor.js
android-4.0
blockingqueue
static-variables
fileutils
noir
drawtext
requestfactory
longjmp
web-analytics-tools
self-reference

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