【发布时间】:2018-03-21 06:17:38
【问题描述】:
我有一个 充满数据的数组在 tableView 单元格中加载图像。但是我得到了轻微的滞后(更多的故障)当表格视图在图像索引上滚动时。
数组包含数据(似乎滞后更大的字节)
以字节为单位的数据(624230 字节)
以字节为单位的数据(1619677 字节)
以字节为单位的数据(2257181 字节)
以字节为单位的数据(1120275bytes)
不确定如何在加载数据时正确使用 Async。
struct messageCellStruct {
let message: String!
let photoData: Data!
}
var messageArray = [messageCellStruct]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
let message2 = cell?.viewWithTag(2) as! UITextView
var photoUploadData = messageArray[indexPath.row].photoData
let main = DispatchQueue.main
let background = DispatchQueue.global()
let helper = DispatchQueue(label: "another_thread")
if(photoUploadData != nil){
print("Data in Bytes\(String(describing: photoUploadData))")
let fullString = NSMutableAttributedString(string: "")
let image1Attachment = NSTextAttachment()
let newImageWidth = (self.message.bounds.size.width - 20 )
let messageDisplayString = self.messageArray[indexPath.row].message
background.async {
image1Attachment.image = UIImage(data: photoUploadData!)
}
image1Attachment.bounds = CGRect.init(x: 0, y: 0, width: newImageWidth, height: 200)
let image1String = NSAttributedString(attachment: image1Attachment)
fullString.append(image1String)
fullString.append(NSAttributedString(string: messageDisplayString!))
message2.attributedText = fullString
message2.textColor = .white
message2.font = UIFont.systemFont(ofSize: 17.0)
}else {
message2.text = self.messageArray[indexPath.row].message
}
return cell!
}
我首先引入 Async 的原因是因为滞后。无论有没有异步,它都会滞后。
【问题讨论】:
-
你为什么不简单地使用SDWebImage 来加载表格单元格中的图像。
UI工作永远不应该在backgroundQueue中完成。如果您在后台下载任何数据,则在显示时执行mainQueue。 -
我有 Alamofire 但我不知道如何将 SDWebImage 或 AlamoFire 与 NSAttachment 集成。它们非常适合 UIImageViews。
-
此外,如果您在
cellForRowAtIndexPath:方法中执行下载任务,您将不得不处理正在进行的请求,因为此方法会多次调用。如果您想避免额外的头痛,请为此使用任何库。 -
好的,但是为什么需要
TextView中的图像?请提及您的要求,因为通常没有人这样做。 -
如果不这样做,我不知道如何以有组织的方式正确实现 imageView 和 textView。
标签: ios swift uitableview asynchronous swift4