Ios 在swift中异步加载图像

Ios 在swift中异步加载图像,ios,swift,Ios,Swift,我想在表视图单元格的视图顶部显示一个图像 我有以下代码异步加载该图像并将其添加到单元格中: if let image = value?["image"] { let bookImageUrl = URL(string: image as! String) let data = try? Data(contentsOf: bookImageUrl!) //make sure you

我想在表视图单元格的视图顶部显示一个图像

我有以下代码异步加载该图像并将其添加到单元格中:

 if let image = value?["image"]  {
                            let bookImageUrl =  URL(string: image as! String)
                            let data = try? Data(contentsOf: bookImageUrl!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
                            DispatchQueue.main.async {
                                if data != nil {
                                    let imageView = UIImageView(image: UIImage(data: data!));
                                    imageView.frame = CGRect(x: 0,
                                                             y: 95,
                                                             width: cell.frame.size.width,
                                                             height: 150)
                                    imageView.contentMode = .scaleAspectFill
                                    imageView.isUserInteractionEnabled = false
                                    cell.addSubview(imageView)

                                    let label = UILabel(frame: CGRect(x: 10,
                                                                      y: cell.frame.size.height-60,
                                                                      width: cell.frame.size.width,
                                                                      height: 50));
                                    label.textColor = UIColor.black
                                    label.backgroundColor = UIColor.init(red: 1, green: 1, blue: 1, alpha: 0.5)
                                    label.font = UIFont(name: "CeraPro-Bold", size: 16)
                                    label.text = "  \(title)"
                                    cell.addSubview(label)
                                }
                            }
                        }

不幸的是,有时图像无法加载。我做错了吗?

如果您使用的是
tableView.dequeueReusableCell(带有标识符:“cellIdentifier”,for:indexath)
func tableView(u-tableView:UITableView,cellForRowAt indexath:indexath)->UITableView cell
中,UITableView对这些单元格进行重用

正如您提到的问题一样,有时图像无法显示,这可能是因为
UITableView
正在重用单元格,因此,如果对每个
if
语句都使用
else
,效果会更好。或者,您可以使用或之类的内容进行图像缓存


还请注意,由于
UITableView
确实重用了每个单元格,因此最好在以编程方式添加任何视图之前,删除所有子视图或在类中为“UITableViewCell”创建一个变量,如在您的代码
cell.addSubview(imageView)
cell.addSubview(标签)中
每次重复使用和URL检查时,
图像视图
标签
都会被反复初始化和添加,在这里,您可以为单元格中的
label
imageview
创建一个变量,只有当变量为
nil
时才初始化,然后分配图像。

如果您像我一样懒惰,并且允许使用第三方框架,您可以使用像翠鸟这样的框架来完成。只要看看你的代码,你的网络电话在哪里?看看这个教程