【问题标题】:Q: SearchBar Tableview with JSON File问:带有 JSON 文件的 SearchBar Tableview
【发布时间】:2023-03-30 00:48:02
【问题描述】:

我需要一些帮助才能将 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"
        },

这是我的视图控制器:https://www.imagebanana.com/s/1193/29VvUoAs.html

有人可以帮帮我吗?提前致谢!!

【问题讨论】:

    标签: ios json swift uitableview searchbar


    【解决方案1】:

    首先,您需要为搜索到的答案定义一个字典:

    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]

    【讨论】:

    • 谢谢,我有几个错误,我添加代码后无法使用覆盖和超级......
    • 你能复制错误信息吗?我的代码会导致这些错误吗?
    • 抱歉我回复晚了,我成功了。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 2012-02-15
    • 1970-01-01
    相关资源
    最近更新 更多