gpt4 book ai didi

swift - 添加约束时出现 EXC_BAD_INSTRUCTION

转载 作者:搜寻专家 更新时间:2023-11-01 06:11:32 27 4
gpt4 key购买 nike

在我尝试从项目中删除 Storyboard之前,我的仪表板 View 工作正常。我使用 git 创建了一个新分支并开始删除 Storyboard并遇到了这个问题。这是我如何进入仪表板屏幕的基本设置。

// 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

最佳答案

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

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

return label
}()

关于swift - 添加约束时出现 EXC_BAD_INSTRUCTION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55800406/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com