[英]Swift3 - UIImageView isn't appearing from parsed JSON data
嘿,我的第一個問題很樂意為您提供幫助。 我花了很長時間瀏覽論壇,但仍在努力了解我在哪里出錯了。 URL字符串可以從JSON解析,但是在我創建的UIImageView中沒有顯示為圖像。 該代碼可以正常編譯,並且其他所有內容都可以顯示。 我假設我必須將類型為String的URL轉換為UIImageView,但是我不斷收到錯誤消息。
這是EventCell類的代碼段。
class EventCell: UICollectionViewCell {
var event: Event? {
didSet {
if let eventName = event?.title {
eventTitle.text = eventName
}
eventSubtitle.text = event?.subtitle
eventTags.text = event?.tags
if let imageName = event?.imageURL
{
imageView.image = UIImage(named: imageName)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let imageView: UIImageView = {
let iv = UIImageView()
iv.translatesAutoresizingMaskIntoConstraints = false
iv.contentMode = .scaleAspectFill
return iv
}()
這是Event類本身的代碼片段。
var id: NSNumber?
var title: String?
var imageURL: String?
var subtitle: String?
var tags: String?
var desc: String?
override init(){}
init(event: NSDictionary)
{
if let val = event["ID"] as? NSNumber
{
id = val;
}
if let val = event["Title"] as? String
{
title = val;
}
if let val = event["Subtitle"] as? String
{
subtitle = val;
}
if let val = event["Tags"] as? String
{
tags = val;
}
if let val = event["Description"] as? String
{
desc = val;
}
if let val = event["image"] as? String
{
imageURL = val;
}
}
任何幫助將非常感激! 謝謝!
初始化程序UIImage(named:)
需要已存儲在分發包中的圖像的名稱。 在您的情況下,您想從URL
加載圖像。 您應該做的是從String
創建一個URL
,然后將該URL
的內容作為NSData
加載,最后從該Data
創建一個UIImage
。 最快的方法是
if let imageURLString = event?.imageURL {
let imageURL = URL(string: imageURLString!)
let imageData = NSData(contentsOf: imageURL!)
imageView.image = UIImage(data: imageData as! Data)
}
注意
需要考慮的幾點
URL
加載圖像的最佳方法。 您還應該研究async
請求。 但是,這是最快的實現,應該可以使代碼正常工作 Swift 3
語法。 如果您正在使用的話,我假設您可以將其轉換為Swift 2
根據Apple文檔, UIImage(named:)
需要應用程序包中名稱的名稱。 您可以在dataWithContentsOfURL:
方法中傳遞圖像的url。 盡管使用這種方法很好,但是您只需要像處理dataWithContentsOfURL:那樣異步處理,它是一個同步請求並阻塞主線程,直到下載完成。
考慮使用SDWebImage一個UIImageView擴展,它添加了用於管理圖像下載和顯示的功能。 它還支持一個占位符圖像,您可以提供該圖像以指示下載正在進行中。
希望能幫助到你。 快樂編碼!
添加此擴展名
extension UIImageView {
public func imageFromUrl(urlString: String) {
if let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if (error != nil) {
print(error?.localizedDescription ?? "no errror")
}
else {
if let image = UIImage(data: data!) {
DispatchQueue.main.async {
self.image = image
}
}
}
}).resume()
}
}
}
用法:
imageView.imageFromUrl(urlString: "http://linktoyourimage.com")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.