我正在尝试制作一个简单的可重用组件(实际上完全是空的,只是一个背景色来区分它),但是当我尝试使用 IBDesignable 装饰器使其可在 XCode Interface Builder 编辑器中显示时,它给了我一个错误:
Failed to render and update auto layout status for AnnounceVC: The agent crashed.
这个错误似乎来 self 的 XIB 组件及其 swift 类。
这是我的AnnounceBubbleView类代码:
import UIKit
@IBDesignable class AnnounceBubbleView: UIView {
@IBOutlet var contentView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(contentView)
}
required init(coder: NSCoder) {
super.init(coder: coder)!
}
}
当我进入 DiagnosticReports 文件夹并发现崩溃时,它给出了以下信息:
Sleep/Wake UUID: F0240558-7F85-40FC-ADCC-7E95493F1BAA
Time Awake Since Boot: 2700 seconds
Time Since Wake: 2300 seconds
System Integrity Protection: enabled
Crashed Thread: 0
Exception Type: EXC_BAD_INSTRUCTION (SIGILL)
Exception Codes: 0x0000000000000001, 0x0000000000000000
Exception Note: EXC_CORPSE_NOTIFY
Termination Signal: Illegal instruction: 4
Termination Reason: Namespace SIGNAL, Code 0x4
Terminating Process: exc handler [3224]
Application Specific Information:
CoreSimulator 587.35 - Device: iPhone 8 (07FC5929-A66D-4560-8FBE-39DF290CD7EB) - Runtime: iOS 12.2 (16E226) - DeviceType: iPhone 8
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
我尝试使用
required init?(coder: NSCoder) {
super.init(coder: coder)
}
但是它给了我同样的错误,如果我不输入可选或强制值,XCode 将无法构建。
编辑
如果我删除“addSubview”部分,那么 UIView 就不是我的自定义 View ,无论是在 IB 上还是在 iOS 模拟器中。这是一个空白的 UIView
代码:
override init(frame: CGRect) {
super.init(frame: frame)
}
override required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
编辑2
我不会以编程方式实例化它,我希望能够在 Storyboard 中预览它。
你有什么想法吗?
如果文章不够清晰,请随时帮助我改进我的帖子,我对 Swift 和 XCode 还算陌生。
最佳答案
在init过程中,contentView还没有初始化,所以是nil, 尝试执行
addSubview(contentView)
确实会导致崩溃,它会尝试强制解开一个零值
如果您的 View 需要从 Storyboard/nib 文件实例化,则不必首先添加 subview
如果您以编程方式实例化它,您需要先实例化 contentView,然后再尝试调用 addSubview
关于ios - 自定义 UIView 类中重写 init 时为 "Unexpectedly found nil while implicitly unwrapping an Optional value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56885070/