[英]Changing UIImageView’s image doesn’t work
我有一個結構,其中包含一個名為userProfileImage的靜態變量,該結構位於名為UserProfilePage.swift的視圖控制器中,以下是代碼:
struct UserProfile {
static let userProfileImage = UIImageView(image: #imageLiteral(resourceName: "profilePicture"))
}
class UserProfilePage: UIViewController {
// Some code that sets the userProfileImage to another image
}
以下代碼位於另一個具有稱為下載結構的swift文件中:
struct Downloads {
guard let profilePicURL = URL(string: profilePictureString) else {
UserProfile.userProfileImage.image = UIImage(named: "profilePicture")
print("Profile picture set to default profile picture")
return
}
// Some code
}
當profilePicURL
不為空時,將執行一些代碼,但是當它為空(等於""
)時,將執行else塊內的代碼。 問題在於配置文件圖片不會改變,它只是在else塊內執行print語句。 有人知道我的代碼有什么問題嗎?
首先,您必須更改userProfileImage 。 這應該是一個var而不是** static let。
您可以在代碼中使用帶異步調用的if let語句。 請嘗試以下代碼。
let profilePictureString = "http://SOME URl STRING.."
if let profilePicURL = URL(string: profilePictureString){
// Plcae Your Network Code Here.
} else {
DispatchQueue.main.async {
UserProfile.userProfileImage.image = UIImage(named: "profilePicture")
print("Profile picture set to default profile picture")
}
}
您可以調用setNeedsDisplay()
來更新imageview
DispatchQueue.main.async {
UserProfile.userProfileImage.image = UIImage(named: "profilePicture")
UserProfile.userProfileImage.setNeedsDisplay()
}
使用圖片文字
struct Downloads {
guard let profilePicURL = URL(string: profilePictureString) else {
UserProfile.userProfileImage.image = imageLiteral(resourceName: "profilePicture")
print("Profile picture set to default profile picture")
return
}
// Some code
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.