我有一个tableview用代码创建的(没有storyboard):
tableview
storyboard
class MSContentVerticalList: MSContent,UITableViewDelegate,UITableViewDataSource { var tblView:UITableView! var dataSource:[MSC_VCItem]=[] init(Frame: CGRect,DataSource:[MSC_VCItem]) { super.init(frame: Frame) self.dataSource = DataSource tblView = UITableView(frame: Frame, style: .Plain) tblView.delegate = self tblView.dataSource = self self.addSubview(tblView) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: nil) let record = dataSource[indexPath.row] cell.textLabel!.text = record.Title cell.imageView!.downloadFrom(link: record.Icon, contentMode: UIViewContentMode.ScaleAspectFit) cell.imageView!.frame = CGRect(x: 0, y: 0, width: 100, height: 100) print(cell.imageView!.frame) cell.detailTextLabel!.text = record.SubTitle return cell } }
在另一堂课中,我有一个扩展方法来下载图像异步:
extension UIImageView { func downloadFrom(link link:String?, contentMode mode: UIViewContentMode) { contentMode = mode if link == nil { self.image = UIImage(named: "default") return } if let url = NSURL(string: link!) { print("\nstart download: \(url.lastPathComponent!)") NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, _, error) -> Void in guard let data = data where error == nil else { print("\nerror on download \(error)") return } dispatch_async(dispatch_get_main_queue()) { () -> Void in print("\ndownload completed \(url.lastPathComponent!)") self.image = UIImage(data: data) } }).resume() } else { self.image = UIImage(named: "default") } } }
我在其他地方使用了此功能并正常工作,根据我的日志,我了解到下载的图像没有问题(渲染单元时),下载图像后,单元UI未更新。
我也尝试使用像Haneke这样的缓存库,但是问题存在并且没有改变。
请帮助我理解错误
谢谢
设置图像后,您应该致电 self.layoutSubviews()
self.layoutSubviews()
编辑:从改正setNeedsLayout为layoutSubviews
setNeedsLayout
layoutSubviews