【发布时间】:2019-11-25 14:26:48
【问题描述】:
我正在使用 XCode 11 并尝试在我的代码中使用委托。但是,它给了我一个错误:Unexpectedly found nil while implicitly unwrapping an Optional value
我以前使用过协议和委托,但从未遇到过这个问题。有人可以帮我弄清楚可能是什么问题吗?提前致谢。
这是我的代码:
class RedScreenVC: UIViewController {
var delegate: NavDelegate!
var redView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
var navigateButton: UIButton = {
let button = UIButton(frame: CGRect(x: 200, y: 350, width: 150, height: 50))
button.setTitle("Navigate", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
button.backgroundColor = .blue
return button
}()
@objc func buttonAction(){
if self.redView.backgroundColor == .gray {
self.redView.backgroundColor = .systemPink
}
}
override func viewDidLoad() {
navigateButton.layer.cornerRadius = 25
redView.backgroundColor = UIColor.gray
delegate.navigate(text: "Navigation Success", isShown: true)
view.addSubview(redView)
view.addSubview(navigateButton)
}
}
这是我创建的委托协议:
protocol NavDelegate {
func navigate(text: String, isShown: Bool)
}
【问题讨论】:
-
请添加RedScreenVC的演示代码。
-
让 navigateButton 变得懒惰
lazy var navigateButton: UIButton =。因为它是您的代码addTarget(self,在没有 self 时运行 -
你在哪里创建代理?可能是委托是空的,所以您会看到错误。并且您应该使用可选值并避免使用强制展开。
标签: swift delegates protocols xcode11 unwrap