首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift 3表搜索

Swift 3表搜索
EN

Stack Overflow用户
提问于 2016-12-24 02:52:02
回答 0查看 789关注 0票数 1

我已经使用来自远程服务器的json数据填充了一个表。

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

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

姓名、公司、职务等

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

我用正确的方式来处理这个问题吗?

代码语言:javascript
复制
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()

    }
}
EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41306527

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档