swift - 在 UIImage 中展开可选时发现 nil

标签 swift

我是 swift 的新手,不知道如何以编程方式更改 UIImageView 中的图片。到目前为止我已经试过了:

if let image = UIImage(named: "mouse.jpg") {
    imageView.image = image
    print("image set")
}

但它会在解包一个可选的致命异常时导致找到 nil。

mouse.jpg 和swift文件在同一个文件夹下,可以在Xcode的inspector中设置为image views image。

像这样将代码包装在另一个代码中:

if let iv = imageView{
    if let image = UIImage(named: "mouse.jpg"){
        iv.image = image
    }
}

修复了 nil 错误,但根本不改变 Storyboard中设置的图片。

任何想法都会有帮助

最佳答案

如果 if 中的这段代码执行,它看起来可能是您对 imageView 的引用而不是图像本身的问题,因为这里的条件需要 UIImage 进行初始化适本地。我猜你正在使用隐式展开的可选存储对 imageView 的引用,例如:var imageView: UIImageView!

如果您使用的是@IBOutlet,您是否检查过它是否连接正确?在设置 image 属性之前,您确定您有 UIImageView 的实际实例吗?

关于swift - 在 UIImage 中展开可选时发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43481627/

相关文章:

ios - 类型 'UITableViewCell' 的值没有成员

ios:Socket.io 中的 Json

ios - 如何使用 Swift 将 "Done"按钮添加到 iOS 中的小键盘?

swift - 快速将图像从一个 View Controller 传递到另一个 View Controller

swift - 使用主键列表过滤从 Realm 查询多个对象

swift - 如何在 Web 套接字中制作红蜘蛛的单例管理器类

ios - UITextField attributedPlaceholder 颜色和不透明度在 swift 4

ios - 我们是否必须生成并使用客户端库才能使用 Google App Engine 的端点?

objective-c - 如何将 Objective C View Controller 推送到 Swift View Controller

swift - 如何以编程方式在 ScrollView Controller 中放置一个段落?