UITableView 慢

UITableView Slow

我是 Swift 的新手,我已经设置了一个 table 视图,它从 JSON 提要中提取数据并将其加载到 table。

table 加载正常,但是当 table 中有超过 10 个单元格时,它变得缓慢且有些滞后,特别是它到达顶部和底部(我想这是在哪里正在重复使用一个单元格)。

有人会好心地看看我的代码并解释为什么它会这样做吗?我已经实现了 SDWebImage,它有帮助但仍然不理想:

 var tableData = [String]()
     var tableAvailable = [String]()
     var tableImages = [String]()
     var tableDesc = [String]()
     var tablePin = [String]()

    override func viewDidAppear(_ animated: Bool) {

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

        self.tableData.removeAll(keepingCapacity: false)
        self.tableAvailable.removeAll(keepingCapacity: false)
        self.tableImages.removeAll(keepingCapacity: false)
        self.tableDesc.removeAll(keepingCapacity: false)


        let url = NSURL(string: "https://www.asmserver.co.uk/sally/parsexml.php")!
        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]] {

                        for item in jsonResult {
                            guard let name = item["display-name"] as? String else { continue }

                            if (self.tableData.contains(item["display-name"] as! String)) {

                            }else{
                            self.tableData.append(name)

                            guard let available = item["status"] as? String else { continue }

                            self.tableAvailable.append(available)

                            guard let image = item["image-url"] as? String else { continue }

                            self.tableImages.append(image)

                            guard let desc = item["short-desc"] as? String else { continue }

                            self.tableDesc.append(desc)

                            guard let pin = item["agent-id"] as? String else { continue }

                            self.tablePin.append(pin)
                            }
                        }
                    }
                } 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()
    }

    override func viewDidLoad() {

        if revealViewController() != nil {
            menuButton.addTarget(self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:)), for: UIControlEvents.touchUpInside)
            self.view.addGestureRecognizer(revealViewController().panGestureRecognizer())
               }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.tableData.count
    }


    // 3
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell  {
        let cell: TblCell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! TblCell
        cell.lblCarName.text = tableData[indexPath.row]

        let url = NSURL(string: "\(tableImages[indexPath.row])")
           if let data = NSData(contentsOf: url as! URL) {

            cell.imgCarNane.sd_setImage(with: (string: url) as URL!)
        }
               cell.pinLabel.text = tablePin[indexPath.row]

                if(tableAvailable[indexPath.row] == "Busy"){
                   cell.onlineIcon.image = UIImage(named: "livefeedofflineicon.png")
                }
                 if (indexPath.row % 2 == 0){
                cell.contentView.backgroundColor = UIColor(red: 237/255.0, green: 234/255.0, blue: 234/255.0, alpha: 1.0)
               }

        return cell
    }

    // 4
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("Row \(indexPath.row) selected")
    }

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

我想在你的 cellForRowAt 中,这条线让它有点慢

if let data = NSData(contentsOf: url as! URL) {
    cell.imgCarNane.sd_setImage(with: (string: url) as URL!)
}

NSData(contentsOf: url as! URL) 有点慢

只需删除 if let 子句,因为 SDWebImage 处理 nil url 本身,只需编写

cell.imgCarNane.sd_setImage(with: (string: url) as URL!)

所以你的cellForRowAt数据源方法现在会变成这样

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell  {
        let cell: TblCell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! TblCell
        cell.lblCarName.text = tableData[indexPath.row]

        let url = NSURL(string: "\(tableImages[indexPath.row])")
            cell.imgCarNane.sd_setImage(with: (string: url) as URL!)
               cell.pinLabel.text = tablePin[indexPath.row]

                if(tableAvailable[indexPath.row] == "Busy"){
                   cell.onlineIcon.image = UIImage(named: "livefeedofflineicon.png")
                }
                 if (indexPath.row % 2 == 0){
                cell.contentView.backgroundColor = UIColor(red: 237/255.0, green: 234/255.0, blue: 234/255.0, alpha: 1.0)
               }

        return cell
    }

我希望修复延迟