栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用swift在表格视图中实现图像的延迟加载

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用swift在表格视图中实现图像的延迟加载

旧解决方案:

由于您没有显示任何代码。

这是给你的例子。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {    // try to reuse cell    let cell:CustomCell = tableView.dequeueReusableCellWithIdentifier("DealCell") as CustomCell    // get the deal image    let currentImage = deals[indexPath.row].imageID    let unwrappedImage = currentImage    var image = self.imageCache[unwrappedImage]    let imageUrl = NSURL(string: "http://staging.api.cheapeat.com.au/deals/(unwrappedImage)/photo")    // reset reused cell image to placeholder    cell.dealImage.image = UIImage(named: "placeholder")    // async image    if image == nil {    let request: NSURLRequest = NSURLRequest(URL: imageUrl!)    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in        if error == nil { image = UIImage(data: data) self.imageCache[unwrappedImage] = image dispatch_async(dispatch_get_main_queue(), {     cell.dealImage.image = image })        }        else {        }    })    }    else{        cell.dealImage.image = image    }  return cell}

请遵循本教程以获取更多信息。希望这会帮助你。

新解决方案:

这是我的朋友Leo Dabus创建的扩展,使用起来
非常简单:

extension UIImageView {    func downloadImageFrom(link link:String, contentMode: UIViewContentMode) {        NSURLSession.sharedSession().dataTaskWithURL( NSURL(string:link)!, completionHandler: { (data, response, error) -> Void in dispatch_async(dispatch_get_main_queue()) {     self.contentMode =  contentMode     if let data = data { self.image = UIImage(data: data) } }        }).resume()    }}

现在,在您的

cellForRowAtIndexPath
方法中,以这种方式将图像分配给单元格:

cell.cellImageView.image = UIImage(named: "placeholder")  //set placeholder image first.cell.cellImageView.downloadImageFrom(link: imagelinkArray[indexPath.row], contentMode: UIViewContentMode.ScaleAspectFit)  //set your image from link array.

正如Rob在评论中建议的那样,您可以使用一些有用的库:

  1. https://github.com/Alamofire/AlamofireImage
  2. https://github.com/onevcat/Kingfisher
  3. https://github.com/rs/SDWebImage
  4. https://github.com/kean/DFImageManager


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/446438.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号