以下是我在實際專案中的一個簡化專案,以突出問題。
我有一個專案,我在其中添加了一個帶有 UIHostingController 的 SwiftUI 視圖,頂部的狀態欄是透明的。我在滾動 SwiftUI 視圖時看到它。
很容易重新創建,使用故事板創建一個新的 iOS 專案,并ViewController使用 NavigationView 將其嵌入到故事板中。
然后將ViewController內容替換為:
import UIKit
import SwiftUI
final class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let hostingController = UIHostingController(rootView: ScrollView { MySwiftUIView() })
self.addChild(hostingController)
view.addSubview(hostingController.view)
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
hostingController.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
hostingController.view.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
hostingController.view.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.backgroundColor = UIColor.yellow
self.title = "MyTitle"
}
}
struct MySwiftUIView: View {
var body: some View {
ZStack {
Color.green
ScrollView {
VStack {
ForEach(0...100, id: \.self) { index in
Text("This is line \(index)")
}
}
}
}
}
}
狀態欄是透明的,并顯示視圖的白色背景:

當我開始滾動時MySwiftUIView,狀態欄是透明的就更加明顯了:

我四處尋找解決方案,因為我希望狀態欄與導航欄具有相同的顏色,并且不在狀態欄中顯示來自 SwiftUI 視圖的內容。但到目前為止,我還沒有找到解決方案。
uj5u.com熱心網友回復:
嘗試改變:
hostingController.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
到
hostingController.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
我不確定??,這是您的預期結果,但它確實消除了SwiftUI內容重疊。
uj5u.com熱心網友回復:
這也是一個技巧:
func setStatusBar() {
if #available(iOS 13, *)
{
let keyWindow = UIApplication.shared.connectedScenes
.filter({$0.activationState == .foregroundActive})
.compactMap({$0 as? UIWindowScene})
.first?.windows
.filter({$0.isKeyWindow}).first
let statusBar = UIView(frame: (keyWindow?.windowScene?.statusBarManager?.statusBarFrame) ?? CGRect(x: 0, y: 0, width: screenWidth, height: statubarHeight))
statusBar.backgroundColor = .green
keyWindow?.addSubview(statusBar)
} else {
let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
if statusBar.responds(to:#selector(setter: UIView.backgroundColor)) {
statusBar.backgroundColor = .green
}
UIApplication.shared.statusBarStyle = .lightContent
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/425580.html
標籤:IOS 迅速 迅捷 uihostingcontroller
