ios - 设置图像 UILabel swift 的问题 - 在展开可选时发现 nil

标签 ios swift uilabel option-type

代码目前看起来像这样:

    lazy var placeLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor(patternImage: UIImage(named: "placelabel")!)
        label.translatesAutoresizingMaskIntoConstraints = false

        return label
    }()

我不确定为什么,但是当我输入 label.backgroundColor() 时,程序无法运行并在该行中断。

“ fatal error :在展开可选值时意外发现 nil”

当我删除它并继续我的设置时,它似乎运行良好。我已经看到其他关于此类问题的评论说调用命令时未设置 View ,但我几乎用我的按钮和诸如此类的东西做完全相同的事情,并且一切正常。

知道为什么会这样吗?

谢谢

最佳答案

在这一行 UIColor(patternImage: UIImage(named: "placelabel")!) 中,您使用 ! 强制展开 UIImage 对象。如果您的项目中不存在名为“placelabel”的图像,应用程序将崩溃,因为您试图解开 nil。

关于ios - 设置图像 UILabel swift 的问题 - 在展开可选时发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38572629/

相关文章:

ios - Swift - 覆盖 UIViewController 与 UITableViewController 中的函数

iphone - 如何向 UILabel 添加滚动功能

ios - 如何在 Swift 中创建 GET、POST 和 PUT 请求?

ios - 带协议(protocol)的 Swift 类扩展 vs 遵守协议(protocol)

ios - 删除 UITableView 中 UITableViewCells 之间的行

ios - 在 UIViewController 上执行的 UIView 上动态创建 UIButton AddTarget

ios - Swift 中的委托(delegate) - 错误无法使用参数列表调用 addTarget

ios - 如何向文本包含 NSBackgroundColorAttributeName 的 UILabel 添加填充

ios - UILabel 中的 Youtube/Instagram 评论风格

objective-c - Objective-C : How to highlight a tableView Cell and keep it highlighted when table is reloaded?