为什么我不能设置图像?
class ViewController:UIViewController,UITableViewDelegate,UITalbeViewDataSource{
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell",for: indexPath) as! CustomTableViewCell
cell.setCell()
return cell
}
}
class CustomTableViewCell:UITableViewCell{
@IBOutlet weak var artworkImage:UIImageView!
func setCell(){
let urlStr = "http://is3.mzstatic.com/image/thumb/Music20/v4/d4/6c/af/d46caf98-ff6c-1707-135d-58d6ed9ea6a2/source/500x500bb.jpg"
let url = URL(strings: urlStr)
let data = try? Data(contentsOf: url!)
if let imageData = data {
self.artworkImage.image = UIImage(data: imageData)
}
}
}
我想在TableView中显示URL目标的图像,但不显示图像。
此图片为日志。
答案 0 :(得分:1)
setCell()
应该是这样的
func setCell(){
let urlStr = "http://is3.mzstatic.com/image/thumb/Music20/v4/d4/6c/af/d46caf98-ff6c-1707-135d-58d6ed9ea6a2/source/500x500bb.jpg"
let url = URL(string: urlStr)
artworkImage.image = UIImage(named: "ic_placeholder")
DispatchQueue.global(qos: .background).async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
if let imageData = data {
self.artworkImage.image = UIImage(data: imageData)
}
}
}
}
图像应该在后台线程下载,否则UI将被阻止。下载图像后,您需要在主线程中进行更改。
最好还有一个占位符图片。
答案 1 :(得分:0)
您正在尝试在后台线程中设置图像,因为您收到此日志。在imageView上显示图像时需要使用主线程,如:
if let imageData = data {
DispatchQueue.main.async(execute: {
self.artworkImage.image = UIImage(data: imageData)
})
}
答案 2 :(得分:0)
尝试使用此Lib作为图像,特别是对于单元格上的ImageView: -
https://github.com/Haneke/HanekeSwift
让URLString = self.items [indexPath.row]
让URL = NSURL(字符串:URLString)!
cell.imageView.hnk_setImageFromURL(URL)
答案 3 :(得分:-1)
细胞:
class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var artworkImage:UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setCell(){
let urlStr = "http://is3.mzstatic.com/image/thumb/Music20/v4/d4/6c/af/d46caf98-ff6c-1707-135d-58d6ed9ea6a2/source/500x500bb.jpg"
let url = URL(string: urlStr)
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
if let imageData = data {
self.artworkImage.image = UIImage(data: imageData)
} }
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
也别忘了。设置App Transport Security Settings
。
祝你好运