画像をURLから読み込み、TableViewのセルに
それぞれが保持しているURL先の画像を表示させる処理を実装しております。
表示するセルの数が何百件とあり、
素早くスクロールすると、別のセルで使っている画像が表示されてしまうことがあるため改善したいです。
scrollView.decelerationRate = UIScrollViewDecelerationRateFast
上記を指定してスクロール速度を下げてみましたが、
解決には至りませんでした。
SDWebImageというライブラリを使用した実装にしようかとも考えましたが、
いまいち実装方法が不明なため、下記のような実装となりました。
何か、解決方法等がございましたら、ご教示お願い致します。
import UIKit import SwiftyJSON class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, URLSessionDelegate { @IBOutlet weak var tableView: UITableView! ~ 省略 ~ // セクション数 func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } // セクションの行数 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return friends.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath:IndexPath) -> UITableViewCell { let cell: CustomCell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath as IndexPath) as! CustomCell cell.setCell(friend: friends[indexPath.row]) return cell }
//非同期 //friend.imageUrlには画像のURLが入っています import UIKit class CustomCell: UITableViewCell { @IBOutlet weak var imageView: UIImageView! ~ 省略 ~ override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func setCell(friend :Friend) { let req = URLRequest(url: NSURL(string:friend.imageUrl as String)! as URL, cachePolicy: .returnCacheDataElseLoad); //追記 let urlStay = req.url let conf = URLSessionConfiguration.default; let session = URLSession(configuration: conf, delegate: nil, delegateQueue: OperationQueue.main); session.dataTask(with: req, completionHandler: { (data, resp, err) in //追記 if((err) == nil && urlStay == resp?.url){ //Success let image = UIImage(data:data!) self.imageView.image = image; }else{ //Error print("AsyncImageView:Error \(err?.localizedDescription)"); } }).resume(); } }