添加约束时EXC_BAD_INSTRUCTION

时间:2019-04-22 20:03:17

标签: swift

在我尝试从项目中删除情节提要之前,我的仪表板视图运行良好。我使用git创建了一个新分支,并开始删除情节提要,并遇到了这个问题。这是我如何进入仪表板屏幕的基本设置。

// AppDelegate.swift 

window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = MainTabController()
// MainTabController
let dashboard = DashboardViewController()
let dashboardNavController = UINavigationController(rootViewController: dashboard)
dashboardNavController.tabBarItem.title = "Dashboard"
viewControllers  = [dashboardNavController]
// DashboardViewController.swift

import UIKit

class DashboardViewController: UIViewController {
    var dashboardTitle: UILabel {
        let label = UILabel()
        label.text = "Defatul Dashboard Title"
        label.translatesAutoresizingMaskIntoConstraints = false

        return label
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        view.addSubview(dashboardTitle)

        dashboardTitle.topAnchor.constraint(equalTo: view.topAnchor).isActive = true <-- Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
    }
}

如果我不添加约束,则应用程序可以正常运行,一旦添加约束,我就会收到错误消息。知道为什么吗?

enter image description here

1 个答案:

答案 0 :(得分:4)

问题在于,每次调用dashboardTitle时都会创建一个新标签。您需要将dashboardTitle更改为:

lazy var dashboardTitle: UILabel = {
    let label = UILabel()
    label.text = "Defatul Dashboard Title"
    label.translatesAutoresizingMaskIntoConstraints = false

    return label
}()