使用 SDWebImage 加载图像时出现问题

Issues loading images using SDWebImage

我正在使用 SDWebImage 库加载用户个人资料的图像。奇怪的是,当我打开包含 5 张照片的个人资料时,只有最后一张图片显示在滚动视图中(您可以滚动查看全宽个人资料图片)。但是,如果我关闭视图并重新打开,所有图像都在那里并且看起来很完美。知道发生了什么事吗?这是代码:

func getPhotos(user:PFUser, forKey:NSMutableArray) {

    var p = 0

    for f in forKey {

        if let pic = user.objectForKey(f as! String) as? PFFile {

            var width = Int(phonewidth)
            photoscroll.contentSize = CGSize(width: CGFloat((p + 1) * width), height: phonewidth)
            pageControl.numberOfPages = p + 1

            var position = CGFloat(p*width)

            var imgview = UIImageView(frame: CGRectMake(position, 0, phonewidth, phonewidth))



            imgview.sd_setImageWithURL(NSURL(string: pic.url), completed: {(image: UIImage!, error: NSError!, cacheType: SDImageCacheType, imageURL: NSURL!) in
                imgview.image = image
                self.photoscroll.addSubview(imgview)
                self.userpics.append(image)
                p++
                println("Added: \(f), URL: \(pic.url)" )
            })
        }
    }
}

你增加 p 的时间太晚了,完成块不会 运行 立即,所以你的循环每次 运行s 和你的图像视图都会有相同的 p 值将全部堆叠在一起。

p++ 放在块外。