响应数据Json格式
[
{
"STOCK": "20 Microns Ltd. EOD Prices",
"CODE": "BOM533022"
},
{
"STOCK": "3i Infotech Ltd. EOD Prices",
"CODE": "BOM532628"
},
{
"STOCK": "3m India Ltd. EOD Prices",
"CODE": "BOM523395"
},
{
"STOCK": "7seas Technologies Ltd-$ EOD Prices",
"CODE": "BOM590116"
},
]
模型类SearchPortfolioModel
import Foundation
typealias searchPortfolioModel = [SearchPortfolioModel]
struct SearchPortfolioModel: Codable {
let stock, code: String
enum CodingKeys: String, CodingKey {
case stock = "STOCK"
case code = "CODE"
}
}
PortfolioViewModel
func stockCodeValue(completion: @escaping () -> ()) {
portfolioClient.fetchSearchPortfolio(){ searchPortfolioModel in
self.searchPortfolioModel = searchPortfolioModel
completion()
}
}
struct PortfolioSearch{
var stockName: String
var stockCode: String
}
func portfolioSearchForItemAtIndexPath(indexPath: NSIndexPath) -> (SearchPortfolioModel){
let stockName = searchPortfolioModel?[indexPath.row].stock ?? ""
let stockCode = searchPortfolioModel?[indexPath.row].code ?? ""
return SearchPortfolioModel(stock: stockName, code:stockCode)
}
内部ViewController类中添加了UITableView和UISearchBar。 如何根据提供的响应从UISearchBar搜索数据。 在ViewController中,整个解析数据显示在tableview中
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if(searchActive) {
return filtered.count
}
// return data.count;
return portfolioViewModel.numberOfItemsInPortfolioSearchSection(section: section)
}
func configurationNewsCell (cell: AddPortfolioTableViewCell, forRowAtIndexPath indexPath:NSIndexPath){
let searchPortfolioStocks = portfolioViewModel.portfolioSearchForItemAtIndexPath(indexPath: indexPath as NSIndexPath)
// Filtered data for stock & code need to will update based on search string.
if(searchActive){
cell.lbl_PortfolioStockName?.text = filtered[indexPath.row]
cell.lbl_PortfolioStockCodeName?.text = searchPortfolioStocks.code
} else {
cell.lbl_PortfolioStockName?.text = searchPortfolioStocks.stock
cell.lbl_PortfolioStockCodeName?.text = searchPortfolioStocks.code
}
}
UISearchBar委托方法。
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filtered = searchPortfolioStocks.filter{ $0.stock.range(of: searchText, options: .caseInsensitive) != nil }
if(filtered.count == 0){
searchActive = false;
} else {
searchActive = true;
}
self.tbl_PortfolioSearch.reloadData()
}
我想根据股票和代号搜索它!
答案 0 :(得分:1)
如果我对您的理解正确,则需要使用localizedCaseInsensitiveContains(_:)方法来过滤库存。
filtered = searchPortfolioStocks.filter {
$0.stock.localizedCaseInsensitiveContains(searchText) || $0.code.localizedCaseInsensitiveContains(searchText)
}