Swift - UITableView 滞后于图像

Swift - UITableView lags with images

我的问题是当我向下滚动 UITableView 时,它看起来太慢了。图片从facebook抓取。

我的代码

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("UserCell", forIndexPath: indexPath) as UITableViewCell

        let user = users[indexPath.row] as User //2

        if let nameLabel = cell.viewWithTag(100) as? UILabel { //3
            nameLabel.text = user.name
        }

        if let dateCreatedLabel = cell.viewWithTag(101) as? UILabel {
        dateCreatedLabel.text = user.distance
        }

        if let profilePictureView = cell.viewWithTag(103) as? UIImageView {
            if let url = NSURL(string: "https://graph.facebook.com/\(user.profilePhoto)/picture?type=large") {
                if let data = NSData(contentsOfURL: url){
                    profilePictureView.contentMode = UIViewContentMode.ScaleAspectFit
                    profilePictureView.image = UIImage(data: data)
                }
            }
        }
        return cell
    }

请指教如何让它顺利。

我的天啊,永远不要这样做,不仅在滚动控件中,而且在一般情况下 UI 还有:

data = NSData(contentsOfURL: url)

这就是您 table 滞后的原因,您很幸运,网速很快。如果你的连接速度很慢,你的应用程序就会挂起,可能永远挂起。总是异步地做网络!

此外,当您使网络异步时,您的table视图仍会滞后于此:

UIImage(data: data)

如果您的单元格中有很多控件,即使在这里:

cell.viewWithTag(101)

所以,使用一些库来下载图片,这并不是看起来那么容易的任务,根据你的经验,你不会自己做对的(据我所知)。

为您的电池单独 class 并使用 IB 连接插座。

试试 AFNetworking,它有 UIImageView 下载图片的类别。

我已经找到答案了。使用 Haneke 代替 NSData.

import Haneke

/* .. */

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("UserCell", forIndexPath: indexPath) as UITableViewCell

        let user = users[indexPath.row] as User //2

        if let nameLabel = cell.viewWithTag(100) as? UILabel { //3
            nameLabel.text = user.name
        }

        if let dateCreatedLabel = cell.viewWithTag(101) as? UILabel {
        dateCreatedLabel.text = user.distance
        }

        if let profilePictureView = cell.viewWithTag(103) as? UIImageView {
            if let url = NSURL(string: "https://graph.facebook.com/\(user.profilePhoto)/picture?type=large") {
                    profilePictureView.contentMode = UIViewContentMode.ScaleAspectFit
                    profilePictureView.hnk_setImageFromURL(url!)

            }
        }
        return cell
    }