[英]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.