UISearchBar 从 Json (SWIFT 3) 获取数据
Posted
技术标签:
【中文标题】UISearchBar 从 Json (SWIFT 3) 获取数据【英文标题】:UISearchBar fetching data from Json ( SWIFT 3 ) 【发布时间】:2017-08-09 02:24:58 【问题描述】:我有一个类保存来自我的 api 的数据
class Shops
private var _familiy_id: String?
private var _logo : String?
private var _shopname : String?
var familiy_id : String
return _familiy_id!
var shopname : String
return _shopname!
var Logo : String
return _logo!
init(shopname : String , Logo : String , family_id : String)
self._shopname = shopname
self._logo = Logo
self._familiy_id = family_id
我正在尝试过滤商店名称并在用户编辑搜索栏时将其展开。所以我尝试了这段代码:
var searchActive : Bool = false
var filtered:[Shops] = []
var shops = [Shops]()
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
filtered = searchText.isEmpty ? shops : shops.filter (item: String) -> Bool in
// If dataItem matches the searchText, return true to include it
return item.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil
tableView.reloadData()
但我收到一条错误消息,提示该项目没有成员范围! 抱歉,这是我第一次在我的项目中实现 UISearchBar,所以我正在尝试从其他代码中学习
【问题讨论】:
【参考方案1】:查看此链接How to implement UISearchController in UITableView - SWIFT 并在此函数中添加您的代码func updateSearchResults(for searchController: UISearchController)
试试这个:
// MARK: UISearchResultsUpdating delegate function
// example for search user in userlist and change it as your requirements.
func updateSearchResults(for searchController: UISearchController)
guard let searchString = searchController.searchBar.text else
return
// Filter the data array and get only those userlist that match the search text.
filteredArray = self.userList.filter
let firstName = $0.first_name.lowercased()
let middleName = $0.middle_name.lowercased()
let lastName = $0.last_name.lowercased()
let contactNumber = $0.mobile.lowercased()
let fullName = $0.fullname.lowercased()
return firstName.range(of: searchString.lowercased()) != nil
|| middleName.range(of: searchString.lowercased()) != nil
|| lastName.range(of: searchString.lowercased()) != nil
|| contactNumber.range(of: searchString.lowercased()) != nil
|| fullName.range(of: searchString.lowercased()) != nil
// Reload the tableview.
tableView.reloadData()
希望对你有所帮助
【讨论】:
感谢您的回复。问题是我不知道如何将商店的名称放在过滤器的数组中。到目前为止,它在数组中作为 Datalet filteredArray = shops.filter let shopname = $0.shopname.lowercased() return shopname.range(of: searchString.lowercased()) != nil
你试过上面的代码了吗?它会帮助你,请尝试一下。以上是关于UISearchBar 从 Json (SWIFT 3) 获取数据的主要内容,如果未能解决你的问题,请参考以下文章
iOS,Swift 3 - 当我从详细视图返回后单击取消时,UISearchBar 消失
UISearchbar 并在查看控制器 xcode swift 中传递数据
Swift:UISearchBar,通过 NSPredicate 名字或姓氏查找 Person
如何将 UiSearchBar 的背景颜色更改为黑色-SWIFT
UISearchBar:传递数据;单击的标题与 ListViewController - Swift 中显示的数据不对应