问:带有 JSON 文件的 SearchBar Tableview
Q: SearchBar Tableview with JSON File
我需要一些帮助才能将 SearchBar 添加到我的 ViewController(包括 tableView)中。
我找到了一些示例来显示现有的 tableView 行。
我想在我的 JSON 文件中的 SearchBar 中显示标题。
当我输入 "Störung"(英文错误)时,它应该显示带有 "Störung" 等的每个标题
除 SearchBar 外一切正常,我坚持使用它...
这是我的代码:
import UIKit
class CategoryTableViewController: UITableViewController {
override func prepare(for seque: UIStoryboardSegue, sender: Any?){
let backItem = UIBarButtonItem()
backItem.title = "Zurück"
navigationItem.backBarButtonItem = backItem
}
var categoryNumber: Int?
var answers: [Dictionary<String, AnyObject>]?
var sectionTitle: String?
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedSectionHeaderHeight = 80
tableView.sectionHeaderHeight = UITableViewAutomaticDimension
if let path = Bundle.main.path(forResource: "data", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let questions = jsonResult["questions"] as? [Dictionary<String, AnyObject>] {
for question in questions {
if let id = question["id"] as? Int {
if(categoryNumber! == id)
{
answers = question["answers"] as? [Dictionary<String, AnyObject>]
sectionTitle = question["title"] as? String
}
}
}
}
} catch {
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitle
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.width, height: 100))
let label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.frame = CGRect.init(x: 5, y: 5, width: headerView.frame.width-10, height: headerView.frame.height-10)
label.text = sectionTitle
headerView.addSubview(label)
return headerView
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return answers!.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! CategoryTableViewCell
let answer = answers![indexPath.row]
cell.categoryLabel.text = answer["title"] as? String
let type = answer["type"] as! String
if(type == "question") {
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let answer = answers![indexPath.row]
let type = answer["type"] as! String
if(type == "question") {
let link = answer["link"] as! Int
if let viewController2 = self.storyboard?.instantiateViewController(withIdentifier: "CategoryTableViewController") {
let categoryTableViewController = viewController2 as! CategoryTableViewController
categoryTableViewController.categoryNumber = link
self.navigationController?.pushViewController(viewController2, animated: true)
}
} else {
let link = answer["link"] as! String
if let viewController2 = self.storyboard?.instantiateViewController(withIdentifier: "PDFViewController") {
let pdfViewController = viewController2 as! PDFViewController
pdfViewController.pdfName = link
self.navigationController?.pushViewController(viewController2, animated: true)
}
}
}
}
这是我的 JSON 文件的一部分:
{
"id": 50,
"title": "Sie brauchen Hilfe bei der Fehlersuche/Fehlerbehebung. Wobei brauchen Sie Hilfe?",
"answers": [
{
"type": "question",
"title": "Busstörung",
"link": 60
},
{
"type": "pdf",
"title": "Ein Modul lässt sich nicht mehr auslesen?",
"link": "205.pdf"
},
{
"type": "pdf",
"title": "Modul ersetzt, wie programmiere ich es?",
"link": "206.pdf"
},
这是我的 ViewController : https://www.imagebanana.com/s/1193/29VvUoAs.html
有人可以帮我吗?提前致谢!!
首先,您需要为搜索的答案定义一个字典:
var filteredAnswers: [Dictionary<String, AnyObject>]?
然后,定义一个当用户点击搜索按钮或搜索文本框时的函数:
func searchBarSearchButtonClicked(_ searchBar: UISearchBar){
self.filteredAnswers.removeAll()
if (searchBar.text?.isEmpty)! {
self.filteredAnswers=self.answers
} else {
if self.answers.count > 0 {
for i in 0...self.answers.count - 1 {
let answer = self.answers[i] as [Dictionary<String, AnyObject>]
if answer.title.range(of: searchBar.text!, options: .caseInsensitive) != nil {
self.filteredAnswers.append(answer)
}
}
}
}
tableView.reloadData();
tableView.reloadInputViews();
searchBar.resignFirstResponder()
}
配置完成后,需要在cellForRowAt函数中将let answer = answers![indexPath.row]
改为let answer = filteredAnswers![indexPath.row]
我需要一些帮助才能将 SearchBar 添加到我的 ViewController(包括 tableView)中。 我找到了一些示例来显示现有的 tableView 行。 我想在我的 JSON 文件中的 SearchBar 中显示标题。 当我输入 "Störung"(英文错误)时,它应该显示带有 "Störung" 等的每个标题
除 SearchBar 外一切正常,我坚持使用它...
这是我的代码:
import UIKit
class CategoryTableViewController: UITableViewController {
override func prepare(for seque: UIStoryboardSegue, sender: Any?){
let backItem = UIBarButtonItem()
backItem.title = "Zurück"
navigationItem.backBarButtonItem = backItem
}
var categoryNumber: Int?
var answers: [Dictionary<String, AnyObject>]?
var sectionTitle: String?
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedSectionHeaderHeight = 80
tableView.sectionHeaderHeight = UITableViewAutomaticDimension
if let path = Bundle.main.path(forResource: "data", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let questions = jsonResult["questions"] as? [Dictionary<String, AnyObject>] {
for question in questions {
if let id = question["id"] as? Int {
if(categoryNumber! == id)
{
answers = question["answers"] as? [Dictionary<String, AnyObject>]
sectionTitle = question["title"] as? String
}
}
}
}
} catch {
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitle
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.width, height: 100))
let label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.frame = CGRect.init(x: 5, y: 5, width: headerView.frame.width-10, height: headerView.frame.height-10)
label.text = sectionTitle
headerView.addSubview(label)
return headerView
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return answers!.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! CategoryTableViewCell
let answer = answers![indexPath.row]
cell.categoryLabel.text = answer["title"] as? String
let type = answer["type"] as! String
if(type == "question") {
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let answer = answers![indexPath.row]
let type = answer["type"] as! String
if(type == "question") {
let link = answer["link"] as! Int
if let viewController2 = self.storyboard?.instantiateViewController(withIdentifier: "CategoryTableViewController") {
let categoryTableViewController = viewController2 as! CategoryTableViewController
categoryTableViewController.categoryNumber = link
self.navigationController?.pushViewController(viewController2, animated: true)
}
} else {
let link = answer["link"] as! String
if let viewController2 = self.storyboard?.instantiateViewController(withIdentifier: "PDFViewController") {
let pdfViewController = viewController2 as! PDFViewController
pdfViewController.pdfName = link
self.navigationController?.pushViewController(viewController2, animated: true)
}
}
}
}
这是我的 JSON 文件的一部分:
{
"id": 50,
"title": "Sie brauchen Hilfe bei der Fehlersuche/Fehlerbehebung. Wobei brauchen Sie Hilfe?",
"answers": [
{
"type": "question",
"title": "Busstörung",
"link": 60
},
{
"type": "pdf",
"title": "Ein Modul lässt sich nicht mehr auslesen?",
"link": "205.pdf"
},
{
"type": "pdf",
"title": "Modul ersetzt, wie programmiere ich es?",
"link": "206.pdf"
},
这是我的 ViewController : https://www.imagebanana.com/s/1193/29VvUoAs.html
有人可以帮我吗?提前致谢!!
首先,您需要为搜索的答案定义一个字典:
var filteredAnswers: [Dictionary<String, AnyObject>]?
然后,定义一个当用户点击搜索按钮或搜索文本框时的函数:
func searchBarSearchButtonClicked(_ searchBar: UISearchBar){
self.filteredAnswers.removeAll()
if (searchBar.text?.isEmpty)! {
self.filteredAnswers=self.answers
} else {
if self.answers.count > 0 {
for i in 0...self.answers.count - 1 {
let answer = self.answers[i] as [Dictionary<String, AnyObject>]
if answer.title.range(of: searchBar.text!, options: .caseInsensitive) != nil {
self.filteredAnswers.append(answer)
}
}
}
}
tableView.reloadData();
tableView.reloadInputViews();
searchBar.resignFirstResponder()
}
配置完成后,需要在cellForRowAt函数中将let answer = answers![indexPath.row]
改为let answer = filteredAnswers![indexPath.row]