Swift 3 table 搜索

Swift 3 table search

我使用来自远程服务器的 json 数据填充了 table。

我现在正在尝试添加一个搜索栏来过滤结果。

我面临的问题是我将 json 数据存储在多个数组中。

姓名、公司、职务等

这意味着当用户搜索时,只有名称数组被过滤并正确显示在 table 中,其他信息不同步,因为它保持未过滤状态。

我的处理方式是否正确?

class attendees: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {

    var tableData = ""

    var value:String!

    var searchString = ""

    var firstname: [String] = []
    var lastname: [String] = []
    var fullname: [String] = []
    var company: [String] = []
    var jobtitle: [String] = []
    var image: [String] = []


    var filteredAppleProducts = [String]()
    var resultSearchController = UISearchController()

    @IBOutlet weak var tableView: UITableView!

    @IBOutlet weak var searchBar: UISearchBar!

    override func viewDidLoad() {

        print(value)



        searchBar.delegate = self



        self.tableView.reloadData()

        let nib = UINib(nibName: "vwTblCell2", bundle: nil)
        tableView.register(nib, forCellReuseIdentifier: "cell2")


    }

    override func viewDidAppear(_ animated: Bool) {
        getTableData()

    }


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


        if filteredAppleProducts != []{

            return self.filteredAppleProducts.count
        }
        else
        {

            if searchString != "[]" {
            return self.firstname.count
            }else {
                return 0
            }
        }

    }


    // 3
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell  {
        let cell2: TblCell2 = self.tableView.dequeueReusableCell(withIdentifier: "cell2") as! TblCell2

        print(filteredAppleProducts)


         if filteredAppleProducts != []{

            cell2.nameLabel.text = self.filteredAppleProducts[indexPath.row]

            return cell2
        }
        else
        {
            if searchString != "[]"{
            cell2.nameLabel.text = "\(self.firstname[indexPath.row]) \(self.lastname[indexPath.row])"
                cell2.companyLabel.text = self.company[indexPath.row]
                cell2.jobTitleLabel.text = self.jobtitle[indexPath.row]


                let url = URL(string: "https://www.asmserver.co.uk/wellpleased/backend/profileimages/\(self.image[indexPath.row])")
                let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
                cell2.userImage.image = UIImage(data: data!)

            }
            return cell2


        }
    }

    // 4
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }

    // 5
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 90
    }


    func updateSearchResults(){


        self.filteredAppleProducts.removeAll(keepingCapacity: false)

        let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchString)
        let array = (self.fullname as NSArray).filtered(using: searchPredicate)
        self.filteredAppleProducts = array as! [String]

        self.tableView.reloadData()

        print(filteredAppleProducts)


    }


    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        print("searchText \(searchText)")
        print(filteredAppleProducts)

        searchString = searchText
         updateSearchResults()
           }

    func getTableData(){

        self.firstname.removeAll()
        self.lastname.removeAll()
        self.fullname.removeAll()
        self.company.removeAll()
        self.jobtitle.removeAll()
        self.image.removeAll()


        let defaults = UserDefaults()
        let userid = defaults.string(forKey: "id")

        let url = NSURL(string: "https://www.asmserver.co.uk/wellpleased/backend/searchattendees.php?userid=\(userid!)&eventid=\(value!)")

        print(url)

        let task = URLSession.shared.dataTask(with: url as! URL) { (data, response, error) -> Void in

            if let urlContent = data {

                do {

                    if let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: []) as? [[String:AnyObject]] {


                        var i = 0

                        while i < jsonResult.count {


                            self.firstname.append(jsonResult[i]["firstname"]! as! String)
                            self.lastname.append(jsonResult[i]["lastname"]! as! String)

                            let fname = jsonResult[i]["firstname"]! as! String
                            let lname = jsonResult[i]["lastname"]! as! String
                           let fullname1 = "\(fname) \(lname)"

                            self.fullname.append(fullname1)

                            self.company.append(jsonResult[i]["company"]! as! String)
                            self.jobtitle.append(jsonResult[i]["jobtitle"]! as! String)
                            self.image.append(jsonResult[i]["image"]! as! String)




                            i = i + 1

                        }

                    }

                } catch {

                    print("JSON serialization failed")

                }

            } else {

                print("ERROR FOUND HERE")
            }

            DispatchQueue.main.async(execute: { () -> Void in

                self.tableView.reloadData()

            })

            self.tableView.isUserInteractionEnabled = true
        }

        task.resume()

    }
}

对数据使用结构或class。这样可以更容易地跟踪数据,而且在任何情况下,看起来您都没有任何充分的理由来跟踪七个不同的数组。

举个例子:

struct Data {
    var firstName: String
    var lastName: String
    var fullName: String
    var company: String
    var jobTitle: String
    var image: String
}

并且只填充一个数组:

var dataSource: [Data] = []

使用 属性 名称访问,而不是 arrayName[index]:

let name = dataSource[index].firstName