简体   繁体   English

更改UIImageView的图像不起作用

[英]Changing UIImageView’s image doesn’t work

I've got a struct, which contains a static variable called userProfileImage, this struct is in a view controller called UserProfilePage.swift, here is the code: 我有一个结构,其中包含一个名为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
}

The following code is in another swift file that has a struct called Downloads: 以下代码位于另一个具有称为下载结构的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
}

When profilePicURL is not empty, some code gets executed, but when it is empty (equal to "" ), the code inside the else block gets executed. profilePicURL不为空时,将执行一些代码,但是当它为空(等于"" )时,将执行else块内的代码。 The problem is that the profile picture doesn't change, it just executes the print statement inside the else block. 问题在于配置文件图片不会改变,它只是在else块内执行print语句。 Does anyone know what's wrong with my code? 有人知道我的代码有什么问题吗?

First of all, you have to change your userProfileImage . 首先,您必须更改userProfileImage This Should be a var instead of **static let. 这应该是一个var而不是** static let。

You can use if let statement with an async call in your code. 您可以在代码中使用带异步调用的if let语句。 Please try the following code. 请尝试以下代码。

    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")
        }
    }

You can call the setNeedsDisplay() for update the imageview 您可以调用setNeedsDisplay()来更新imageview

DispatchQueue.main.async {
    UserProfile.userProfileImage.image = UIImage(named: "profilePicture")
    UserProfile.userProfileImage.setNeedsDisplay()
}

use image literal 使用图片文字

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM