ios - 覆盖 UIImageView 的图像

标签 ios swift properties uiimageview overriding

我正在尝试在 Swift 中创建 UIImageView 的子类,以显示从自定义属性(来 self 的模型)中检索到的图像。我使用的代码如下:

class AvatarImageView: UIImageView {
    var userProfile: UserProfile?

    override var image: UIImage? {
        set {}

        get {
            return self.userProfile?.avatar
        }
    }
}

不幸的是,这不起作用。图像永远不会显示。我还尝试调用 setNeedsDisplay,但没有成功。我很乐意提出建议。

最佳答案

你应该使用userProfiledidSet

class AvatarImageView: UIImageView {
    var userProfile: UserProfile? {
        didSet {
            guard let userProfile = userProfile else { return }
            image = userProfile.avatar
        }
    }
}

您覆盖了触发绘图图像的image'set,但它是空的。这意味着无论您设置什么,它都不会执行任何操作。对于get,如果您调用avatarImageView.image,它将返回avatarImageView.userProfile.avatar。这就是您所做的一切。

您要做的是在设置您自己的模型userProfile 时设置图像。 didSet 在设置值后立即被调用。因此,每次设置新值时都会调用 userProfiledidSet,我只是在 didSet 中调用 UIImageView.image = .

阅读此 article

关于ios - 覆盖 UIImageView 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40985092/

相关文章:

android - 如何在 React Native 中开发时间轴屏幕

ios - XCode 中的 ObjC 链接器标志

swift - 在 swift 的条件转场中获取 NSInternalInconsistencyException

swift - 开发 macOS 的辅助应用程序,apiDisabled

java - 使用 JMX 注册和更新应用程序属性

c# - 为什么 FSharpOption 的某些属性(例如 IsSome 和 IsNone)在 C# 中不可见?

ios - 在 Xcode 中创建并附加一个 .txt 文件到电子邮件

ios - 如何从 swift(iOS) 重定向 Skype 应用程序

ios - 在下一个 View 中编辑标签很长

Java属性: � displayed instead of ä