【问题标题】:Swift - UITableView lags with imagesSwift - UITableView 滞后于图像
【发布时间】:2015-02-07 09:40:38
【问题描述】:

我的问题是当我向下滚动 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
    }

请指教如何使它顺利。

【问题讨论】:

标签: ios uitableview swift xcode6


【解决方案1】:

天哪,不仅在滚动控件中,而且在一般 UI 中也不要这样做:

data = NSData(contentsOfURL: url)

这就是为什么您的餐桌滞后,而且您很幸运拥有快速的互联网。如果您的连接速度很慢,您的应用程序将挂起,可能会永远挂起。总是做网络异步!

另外,当你让你的网络异步时,你的 tableView 仍然会滞后:

UIImage(数据:数据)

即使你的单元格中有很多控件:

cell.viewWithTag(101)

所以,使用一些库来下载图像,这令人惊讶地不像看起来那么容易,根据你的经验你不会自己做对的(据我所知)。

为你的单元创建单独的类并使用 IB 连接插座。

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

【讨论】:

  • 那么我该如何解决这个问题呢?
  • @Dato'MohammadNurdin 看到我更新的答案,你用 swift 编码,我认为现在没有那么多库(我用 Objective-c 编码,有几个,尝试采用 AFNetworking f.e. )
  • @Dato'MohammadNurdin 是的,这是来自 AFNetworking 的作者,所以这正是您所需要的。
【解决方案2】:

我已经找到答案了。使用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
    }

【讨论】:

    猜你喜欢
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    相关资源
    最近更新 更多