在 Xcode 中的 iOS 模拟器中运行应用程序时出现黑屏

问题描述 投票:0回答:1

我是 iOS 编程新手,正在学习如何在

UIKit
项目中使用
swift
。我创建了一个简单的项目,在
UIKit
中的 iOS 模拟器 (iOS 16) 上使用
xcode
显示文本消息。以下是我的
ContentView.swift
testApp.swift
文件:

ContentView.swift

import UIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Create a UIWindow instance
        window = UIWindow(frame: UIScreen.main.bounds)
        if window == nil {
            print("Window is nil.")
        } else {
            print("Window is not nil.")
        }
        let viewController = ViewController()
        window?.rootViewController = viewController
        window?.makeKeyAndVisible()
        if window?.rootViewController == nil {
            print("Root view controller is not set.")
        } else {
            print("Root view controller is set.")
        }
        if let rootView = window?.rootViewController?.view {
            print("Root view hierarchy:")
            print(rootView.subviews)
        }
        if let viewController = window?.rootViewController as? ViewController {
            print("Status label text: \(viewController.statusLabel.text ?? "Not set")")
        }      
        return true
    }
}

testApp.swift

import UIKit
class ViewController: UIViewController {
    public var statusLabel = UILabel()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Configure status label
        statusLabel.text = "This is an example"
        statusLabel.textAlignment = .center
        statusLabel.numberOfLines = 0
        statusLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(statusLabel)
        NSLayoutConstraint.activate([
            statusLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            statusLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }
}

它的构建没有任何错误,但是当应用程序在模拟器中打开时,我得到一个没有任何文本的黑色屏幕。打印调试消息

Window is not nil.
Root view controller is set.
Root view hierarchy:
不包含
UILabel
statusLabel
文本。

有人可以告诉我这里出了什么问题吗?

statusLabel
是否未正确初始化?我还在日志中看到消息
[EventDispatcher] Found no UIEvent for backing event of type: 3

提前致谢

P.S:我正在使用

xcode
15.0.1,目标
iPhone
,SDK
iOS
,最小部署
16.0
,排除的架构为空。如果我错过了什么请告诉我

ios swift xcode uikit
1个回答
0
投票

意外地在 Xcode 中创建了 SwiftUI 项目并尝试使用 UIKit。但是,当使用 SwiftUI 而不是 UIKit 时,它可以正常工作。 感谢@matt(在评论中)指出这一点

© www.soinside.com 2019 - 2024. All rights reserved.