首页 > 解决方案 > 在 SWIFTUI 中添加新窗口并使其成为关键窗口

问题描述

我想添加一个新窗口,因为我想创建一个全屏加载程序。我试图在其中添加一个新窗口并将其设置为 rootviewcontroller。但它没有添加到 Windows 层次结构中。下面是我的代码。我正在学习 swiftUI。任何帮助表示赞赏。

let window = UIWindow()
window.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
window.backgroundColor = .blue
window.isHidden = false
window.rootViewController = UIHostingController(rootView: Text("Loading...."))
window.makeKeyAndVisible()

标签: swiftswiftuiswiftui-navigationlink

解决方案


您需要包装 UIActivityIndi​​cator 并使其成为 UIViewRepresentable。

struct ActivityIndicator: UIViewRepresentable {

@Binding var isAnimating: Bool
style: UIActivityIndicatorView.Style

func makeUIView(context: UIViewRepresentableContext<ActivityIndicator>) -> UIActivityIndicatorView {
    return UIActivityIndicatorView(style: style)
}

func updateUIView(_ uiView: UIActivityIndicatorView, context: UIViewRepresentableContext<ActivityIndicator>) {
    isAnimating ? uiView.startAnimating() : uiView.stopAnimating()
  }
}

然后你可以按如下方式使用它——这里是一个加载覆盖的例子。

注意:我更喜欢使用 ZStack,而不是 overlay(:_),所以我确切地知道我的实现 struct LoadingView: View where Content: View {

@Binding var isShowing: Bool
var content: () -> Content

var body: some View {
    GeometryReader { geometry in
        ZStack(alignment: .center) {

            self.content()
                .disabled(self.isShowing)
                .blur(radius: self.isShowing ? 3 : 0)

            VStack {
                Text("Loading...")
                ActivityIndicator(isAnimating: .constant(true), style: .large)
            }
            .frame(width: geometry.size.width / 2,
                   height: geometry.size.height / 5)
            .background(Color.secondary.colorInvert())
            .foregroundColor(Color.primary)
            .cornerRadius(20)
            .opacity(self.isShowing ? 1 : 0)

         }
      }
   }

}

推荐阅读