Swift - 异步加载各网站的favicon图标,并在单元格中显示
(本文代码已升级至Swift3)
主要是复习下如何自定义单元格,单元格中图片的异步加载,以及 didSet 的用法。
1,效果图
2,操作步骤
(1)先创建单元格类:FaviconTableViewCell.swift
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import UIKit class FaviconTableViewCell : UITableViewCell { //此操作队列运行下载的完成处理器 // var operationQueue:OperationQueue? //此单元格显示的URL var url: URL ? { //当URL发生变化 didSet { //显示此文本 self .textLabel?.text = self .url?.host //创建请求 let request = URLRequest (url: self .url!) let session = URLSession .shared let dataTask = session.dataTask(with: request, completionHandler: {(data, response, error) -> Void in //将获取到的数据转化成图像 let image = UIImage (data: data!) //对UI的更新必须在主队列上完成 DispatchQueue .main.async{ //将已加载的图像赋予图像视图 self .imageView?.image = image //图像视图可能已经因为新图像而改变了尺寸 //所以需要重新调整单元格的布局 self .setNeedsLayout() } }) as URLSessionTask //使用resume方法启动任务 dataTask.resume() } } override func awakeFromNib() { super .awakeFromNib() } override func setSelected(_ selected: Bool , animated: Bool ) { super .setSelected(selected, animated: animated) } } |
(2)在 Main.storyboard 中添加一个 Table View,并将 Table View 的 Prototype Cells(原型单元格)数改成 1,Selection(选择样式)改称 No Selection
(3)选中单元格,将样式设为 Basic,并将 Indentifier(标识符)改为 FaviconCell
(4)再把单元格的 Identity Inspector(身份查看器)改为 FaviconTableViewCell
(5)按住 Control 键,拖动表格视图到视图控制器上,分别添加数据源和委托(dataSource 与 delegate)
(6)最后还要在 info.plist 中添加如下配置以支持 http 传输。
1 2 3 4 5 | <key> NSAppTransportSecurity </key> <dict> <key> NSAllowsArbitraryLoads </key> < true /> </dict> |
(7)ViewController.swift 代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | import UIKit class ViewController : UIViewController , UITableViewDelegate , UITableViewDataSource { let hosts = [ "hangge.com" , "163.com" , "baidu.com" , "qq.com" , "taobao.com" ] override func viewDidLoad() { super .viewDidLoad() } //在本例中,只有一个分区 func numberOfSections( in tableView: UITableView ) -> Int { return 1 } //返回表格行数(也就是返回控件数) func tableView(_ tableView: UITableView , numberOfRowsInSection section: Int ) -> Int { return self .hosts.count } //创建各单元显示内容(创建参数indexPath指定的单元) func tableView(_ tableView: UITableView , cellForRowAt indexPath: IndexPath ) -> UITableViewCell { //为了提供表格显示性能,已创建完成的单元需重复使用 let identify: String = "FaviconCell" //同一形式的单元格重复使用,在声明时已注册 let cell = tableView.dequeueReusableCell(withIdentifier: identify) as ! FaviconTableViewCell let host = hosts[indexPath.row] cell.url = url return cell } override func didReceiveMemoryWarning() { super .didReceiveMemoryWarning() } } |

写的很不错,但是为什么不直接用 SDWebImage实现呢...