加载图像后更新单元格
Posted
技术标签:
【中文标题】加载图像后更新单元格【英文标题】:Update a cell after loading images 【发布时间】:2016-09-13 07:52:55 【问题描述】:我在通过 AlamofireImage 加载图像时遇到问题,如何在?或者我必须在 tableviewcell.swift 中提出请求
我的表视图控制器
class NewTableViewController: UITableViewController
var videos = [Video]()
didSet
dispatch_async(dispatch_get_main_queue())
self.tableView.reloadData()
let URL = "https://api.vid.me/channel/1/new"
override func viewDidLoad()
super.viewDidLoad()
let request = Alamofire.request(.GET, self.URL)
request.responseObject (response: Response<NewestVideos, NSError>) in
switch response.result
case .Success(let newest):
self.videos = newest.videos!
print(self.videos)
case .Failure(let error):
print("Request failed with error: \(error)")
...
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! VideoTableViewCell
let video = videos[indexPath.row]
cell.titleLabel?.text = video.title != nil ? video.title! : "no name"
cell.videoImageView?.af_setImageWithURL(NSURL(fileURLWithPath: video.thumbnailUrl!)) //here i make image request from url (and url i get from request in viewdidload)
return cell
...
【问题讨论】:
【参考方案1】:你可以使用 SDWebimage 来加载图片同步,加载完成后做任何你想做的事:
[self.imageView setImageWithURL:[NSURL URLWithString:imageURL]
placeholderImage:[UIImage imageNamed:@"YourPlaceholder.png"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
//... completion code here ...
];
或者创建一个函数来加载带有处理程序完成的图像,看看:
func imageForUrl(urlString: String, completionHandler:(image: UIImage?, url: String) -> ())
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ()in
let downloadTask: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlString)!, completionHandler: (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if (error != nil)
completionHandler(image: nil, url: urlString)
return
if data != nil
let image = UIImage(data: data!)
dispatch_async(dispatch_get_main_queue(), () in
completionHandler(image: image, url: urlString)
)
return
)
downloadTask.resume()
)
并使用它:
yourimage.images = self.imageForUrl("link", completionHandler: (image, url) in
// do s.t
)
你可以创建 UIImage 的扩展
【讨论】:
以上是关于加载图像后更新单元格的主要内容,如果未能解决你的问题,请参考以下文章