如何快速从模型中搜索数据?

时间:2019-04-02 07:14:16

标签: swift

我想使用搜索栏在表视图中搜索一些数据,但是当我尝试在模型中查找数据时,我无法搜索该数据。
我做了一个扩展表视图单元并创建了一个用于搜索数据的搜索栏,但仍然无法在模型中搜索数据。我该如何实现?

这是我的代码:

import UIKit

class FAQViewController: UIViewController, UITableViewDataSource {

    var dataFaq = [modelFAQ]()

    let items = [
        modelFAQ(name: "1. search box", description: "The design led users to instinctively search for their question first before clicking the FAQs"),
        modelFAQ(name: "2.list of FAQs ", description: "Customers clicked around on the FAQs first."),
        modelFAQ(name: "3. customers", description: "top issues first and then use the search for the questions instead of browsing and yielding more relevant results")

        ]

    @IBOutlet fileprivate weak var tableView: UITableView!
    @IBOutlet weak var searchDataBar: UISearchBar!
    fileprivate var indexPaths: Set<IndexPath> = []
    var cellIdentifier = "dataSourceFAQ"

    var searchData = [String]()
    var searching = false

    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupTableView()
        searchDataBar.delegate = self
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if searching {
            return searchData.count
        }else {
            return items.count
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! FAQTableViewCell

        if searching{
            cell.titleLabel.text = searchData[indexPath.row]
        }else{
            cell.titleLabel.text = items[indexPath.row].name
        }

        let nameDetail = self[indexPath].name as? String
        let description = self[indexPath].description


        cell.update(name: nameDetail ?? "0", description: description)


        cell.state = cellIsExpanded(at: indexPath) ? .expanded : .collapsed
        return cell
    }

    override func viewWillAppear(_ animated: Bool) {
        tabBarController?.tabBar.isHidden = true
    }

    private func setupTableView(){
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 200.0
        tableView.separatorStyle = .none
         }

     }

    extension FAQViewController: UITableViewDelegate{
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let cell = tableView.cellForRow(at: indexPath) as!FAQTableViewCell


            cell.state = .expanded
            self.addExpandedIndexPath(indexPath)

            tableView.beginUpdates()
            tableView.endUpdates()
            print("1")
        }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! FAQTableViewCell

        cell.state = .collapsed
        self.removeExpandedIndexPath(indexPath)


        tableView.beginUpdates()
        tableView.endUpdates()
        print("2")
}
}

extension FAQViewController {
    func cellIsExpanded(at indexPath: IndexPath) -> Bool {
        return indexPaths.contains(indexPath)
    }

    func addExpandedIndexPath(_ indexPath: IndexPath) {
        indexPaths.insert(indexPath)
    }

    func removeExpandedIndexPath(_ indexPath: IndexPath) {
        indexPaths.remove(indexPath)
    }
}

extension FAQViewController {
    subscript(indexPath: IndexPath) -> modelFAQ {
        return items[indexPath.row]
    }
}


    extension FAQViewController: UISearchBarDelegate {

        func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

            searchData = searchText.isEmpty ? items: items.filter{ $0.name(searchText)}

            searching = true
            tableView.reloadData()
        }
       }

这是我的表格视图单元格

    import UIKit

    class FAQTableViewCell: UITableViewCell {

        enum cellState{
            case collapsed
            case expanded

            var carretImage: UIImage {
                switch self {
                case .collapsed:
                    return UIImage(named: "ic_arrow_down")!
                case .expanded:
                    return UIImage(named: "ic_arrow_up")!
                }
            }

        }

        @IBOutlet private weak var stackView: UIStackView!
        @IBOutlet private weak var containerView: UIView!
        @IBOutlet weak var titleLabel: UILabel!
        @IBOutlet private weak var carret: UIImageView!
        @IBOutlet private weak var descriptionLabel: UILabel!


        private let expandedViewIndex: Int = 1

        var state: cellState = .expanded {
            didSet{
                toggle()
            }
        }

        override func awakeFromNib() {
            selectionStyle = .none
            containerView.layer.cornerRadius = 5.0
        }

        private func toggle(){
            stackView.arrangedSubviews[expandedViewIndex].isHidden = stateIsCollapsed()
            carret.image = state.carretImage
        }

        private func stateIsCollapsed() -> Bool{
            return state == .collapsed
        }

        func update(name: String, description: String){
            titleLabel.text = name
            descriptionLabel.text = description

        }
    }

这是我的模特

    struct modelFAQ {
        var name: String
        var description: String
    }

2 个答案:

答案 0 :(得分:0)

两个问题:

  1. 您必须将searchData声明为与主数据相同的类型。

    按照命名约定,结构和类名以大写字母开头

    var searchData = [ModelFAQ]()
    
  2. 搜索filter关闭是错误的。写

    searchData = searchText.isEmpty ? items : items.filter{ $0.name.contains(searchText)}
    

    或者如果您要搜索不区分大小写的

    searchData = searchText.isEmpty ? items : items.filter{ $0.name.range(of: searchText, options: .caseInsensitive) != nil }
    

您必须更改cellForRowAt

cell.titleLabel.text = searchData[indexPath.row].name

答案 1 :(得分:0)

  

注意:始终以大写字母

开头的类/结构名称
  • 错误:modelFAQ

  • 正确:ModelFAQ

您犯了一个错误,您必须像下面这样声明您的searchData Array

var searchData = [ModelFAQ]()

在数据源方法中,您必须从ModelFAQ对象获取名称并将其分配给标签。

希望它会对您有所帮助。