在搜索栏iOS swift3中加载带有条目的单元格时,图像无法正确显示

Posted

技术标签:

【中文标题】在搜索栏iOS swift3中加载带有条目的单元格时,图像无法正确显示【英文标题】:image is not displayed correctly while loading cell with entries in searchbar iOS swift3 【发布时间】:2017-06-28 05:02:36 【问题描述】:

在这里,我试图在搜索开始时显示过滤后的数据结果。名称的搜索有效,但我不明白如何通过搜索显示图像。我认为错误在于过滤器内容我是 ios 新手,如有任何帮助,将不胜感激

   import UIKit
    import Foundation
    import SDWebImage

    class TableViewController: UITableViewController,UISearchBarDelegate,UISearchResultsUpdating 
        //var sections = ["recent","old"]
        var TableData:Array<String> = Array <String>()
        //var TableDataRecent:Array<String> = Array <String>()
        var TableImage:Array<String> = Array <String>()
        var appoid:Array<String> = Array <String>()


        var filteredArray:[String]=[]
        var filteredImage:[String]=[]
        let searchController = UISearchController(searchResultsController:nil)


        override func viewDidLoad() 
            super.viewDidLoad()
            getData()
            self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cells")
            searchController.searchResultsUpdater = self
            searchController.dimsBackgroundDuringPresentation=false
            definesPresentationContext=true
            self.tableView.tableHeaderView = searchController.searchBar
            // Do any additional setup after loading the view, typically from a nib.
            tableView.reloadData()
        

        override func didReceiveMemoryWarning() 
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        
        //
        //    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? 
        //
        //        return sections[section]
        //
        //    
        //
        //    override func numberOfSections(in tableView: UITableView) -> Int 
        //        // #warning Incomplete implementation, return the number of sections
        //
        //        return sections.count
        //
        //    



        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
            if searchController.isActive && !searchController.searchBar.isEqual("") 
                return self.filteredArray.count
            
            else
                return TableData.count
            
        

        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
            //here cells is the identifier name of prototype cell

            let cell = self.tableView.dequeueReusableCell(withIdentifier: "cells", for: indexPath)

            if searchController.isActive && !searchController.searchBar.isEqual("")
                cell.textLabel?.text = filteredArray[indexPath.row]
                //cell.imageView?.image = filteredImage[indexPath.row]
    //            print("filteredimage")
    //            print(filteredImage)
    //            print(indexPath.row)
                cell.imageView?.sd_setImage(with: URL(string: TableImage[indexPath.row]), placeholderImage: UIImage(named: "PA"))
                print(TableData[indexPath.row])

                print(appoid[indexPath.row])
            
            else
                cell.textLabel?.text = self.TableData[indexPath.row]
                //cell.imageView?.image = self.TableImage[indexPath.row]
                cell.imageView?.sd_setImage(with: URL(string: TableImage[indexPath.row]), placeholderImage: UIImage(named: "PA"))
            //cell.= appoid[indexPath.row]

            


        return cell
    





    func filterContentForSearch(searchString:String)
        self.filteredArray=self.TableData.filter()nil != $0.range(of:searchString)
     self.filteredImage=self.TableImage.filter()nil != $0.range(of:searchString)

        self.tableView.reloadData()
    


    func updateSearchResults(for searchController: UISearchController) 
        self.filterContentForSearch(searchString: searchController.searchBar.text!)
    




    func getData() 


        var request = URLRequest(url: URL(string: "*********")!)
        //request.httpMethod = "POST"
        //let postString = "date="+x
        //request.httpBody = postString.data(using: .utf8)
        //print(request.httpBody)
        let task = URLSession.shared.dataTask(with: request)  data, response, error in
            guard let data = data, error == nil else                                                  // check for fundamental networking error
                print("error=\(error)")
                return
            

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200            // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(responseString)")

            do

                let json = try JSONSerialization.jsonObject(with: data, options:.allowFragments) as! [String:AnyObject]

                if let stations = json["result"] as? [[String: AnyObject]] 
                    for station in stations 
                        let name = station["patient_name"] as! String
                        //self.login = login_value
                        let profile_pic = station["image"] as! String
                        let status = station["status"] as! String

                        let appo_id = station["id"] as! String
                    //    let appo_id = station["appointment_id"] as! String
                        //let status = station["status"] as! String
                        //let appo_time = station["appointment_time"] as! String
                        //let appo_duration = station["time_duration"] as! String
                        //let reason = station["reason"] as! String
                        print(name,status)

                        self.TableData.append(name)
                        self.TableImage.append(profile_pic)
                        self.appoid.append(appo_id)

                    







                    print(self.TableData)
                    print(self.TableImage)
                    //print(self.items)
                    //self.do_table_refresh();
                    self.tableView.reloadData()

                

            catch 
                print("Error with Json: \(error)")
            



        
        task.resume()



    







【问题讨论】:

你在filteredImage中有url吗? 【参考方案1】:

不要为图像、数据和应用程序保留单独的数组。创建 struct 对象并在 struct 对象上进行搜索。 试试这个,

import UIKit
   import Foundation
   import SDWebImage

   struct TableObject 
    var name: String = ""
    var image: String = ""
    var appoId: String = ""
   

   class TableViewController: UITableViewController,UISearchBarDelegate,UISearchResultsUpdating 
    //var sections = ["recent","old"]
    var tableDataSource: [TableObject] = []

    var filteredArray: [TableObject] = []
    let searchController = UISearchController(searchResultsController:nil)


    override func viewDidLoad() 
        super.viewDidLoad()
        getData()
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cells")
        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation=false
        definesPresentationContext=true
        self.tableView.tableHeaderView = searchController.searchBar
        // Do any additional setup after loading the view, typically from a nib.
        tableView.reloadData()
    

    override func didReceiveMemoryWarning() 
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    
    //
    //    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? 
    //
    //        return sections[section]
    //
    //    
    //
    //    override func numberOfSections(in tableView: UITableView) -> Int 
    //        // #warning Incomplete implementation, return the number of sections
    //
    //        return sections.count
    //
    //    



    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
        if searchController.isActive && !searchController.searchBar.isEqual("") 
            return self.filteredArray.count
        
        else
            return tableDataSource.count
        
    

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
        //here cells is the identifier name of prototype cell

        let cell = self.tableView.dequeueReusableCell(withIdentifier: "cells", for: indexPath)

        if searchController.isActive && !searchController.searchBar.isEqual("")
            cell.textLabel?.text = filteredArray[indexPath.row].name
            //cell.imageView?.image = filteredImage[indexPath.row]
            //            print("filteredimage")
            //            print(filteredImage)
            //            print(indexPath.row)
            cell.imageView?.sd_setImage(with: URL(string: filteredArray[indexPath.row].image), placeholderImage: UIImage(named: "PA"))
        
        else
            cell.textLabel?.text = self.TableData[indexPath.row]
            //cell.imageView?.image = self.TableImage[indexPath.row]
            cell.imageView?.sd_setImage(with: URL(string: tableDataSource[indexPath.row].image), placeholderImage: UIImage(named: "PA"))
            //cell.= appoid[indexPath.row]

        


        return cell
    





    func filterContentForSearch(searchString:String)
        self.filteredArray=self.tableDataSource.filter()nil != $0.name.range(of:searchString)

        self.tableView.reloadData()
    


    func updateSearchResults(for searchController: UISearchController) 
        self.filterContentForSearch(searchString: searchController.searchBar.text!)
    




    func getData() 


        var request = URLRequest(url: URL(string: "*********")!)
        //request.httpMethod = "POST"
        //let postString = "date="+x
        //request.httpBody = postString.data(using: .utf8)
        //print(request.httpBody)
        let task = URLSession.shared.dataTask(with: request)  data, response, error in
            guard let data = data, error == nil else                                                  // check for fundamental networking error
                print("error=\(error)")
                return
            

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200            // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(responseString)")

            do

                let json = try JSONSerialization.jsonObject(with: data, options:.allowFragments) as! [String:AnyObject]

                if let stations = json["result"] as? [[String: AnyObject]] 
                    for station in stations 
                        let name = station["patient_name"] as! String
                        //self.login = login_value
                        let profile_pic = station["image"] as! String
                        let status = station["status"] as! String

                        let appo_id = station["id"] as! String
                        //    let appo_id = station["appointment_id"] as! String
                        //let status = station["status"] as! String
                        //let appo_time = station["appointment_time"] as! String
                        //let appo_duration = station["time_duration"] as! String
                        //let reason = station["reason"] as! String
                        print(name,status)
                        let tableData = TableObject(name: name, image: profile_pic, appoId: appo_id)
                        self.tableDataSource.append(tableData)

                    
                    //print(self.items)
                    //self.do_table_refresh();
                    self.tableView.reloadData()

                

            catch 
                print("Error with Json: \(error)")
            

        
        task.resume()
    

   

【讨论】:

【参考方案2】:

关注这些

不要做单独的数组:

 let arrData = [Any]() // these combined array

获取数据时更改

if let stations = json["result"] as? [[String: AnyObject]] 
                        for station in stations 
                            arrData.append(station)
                        

TableViewDatasource 的变化

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
            if searchController.isActive && !searchController.searchBar.isEqual("") 
                return self.filteredArray.count
            
            else
                return arrData.count
            
        
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
        //here cells is the identifier name of prototype cell

        let cell = self.tableView.dequeueReusableCell(withIdentifier: "cells", for: indexPath)

               if searchController.isActive && !searchController.searchBar.isEqual("")
                     let dictObjects = filteredArray[indexPath.row] as [String: AnyObject]
                  cell.textLabel?.text = dictObjects["name"]
              cell.imageView?.sd_setImage(with: URL(string:  dictObjects["image"]), placeholderImage: UIImage(named: "PA"))
        
        else
        let dictObjects = arrData[indexPath.row] as [String: AnyObject]

            cell.textLabel?.text = dictObjects["name"]
            cell.imageView?.sd_setImage(with: URL(string:  dictObjects["image"]), placeholderImage: UIImage(named: "PA"))
        //cell.= appoid[indexPath.row]

        

    return cell

使用此过滤器

let namePredicate = NSPredicate(format: "name like %@","yourstring");
filteredArray = arrData.filter  namePredicate.evaluate(with: $0) ;
print("names = ,\(filteredArray)");

【讨论】:

以上是关于在搜索栏iOS swift3中加载带有条目的单元格时,图像无法正确显示的主要内容,如果未能解决你的问题,请参考以下文章

如何在已经是 NIB 的 UICollectionViewCell 中加载带有自定义单元格的 UITable

在表格视图单元格中加载和缓存多个 UIImageView 不起作用

如何在 hive 表中加载多行列数据?具有换行符的列

两个带有搜索栏的自定义单元格

在 Handsontable 单元格中加载数组

如何在uitableview中加载数据而不每次都重新加载