Ios 取消回刷时,SwiftUI应用程序冻结,100%CPU

Ios 取消回刷时,SwiftUI应用程序冻结,100%CPU,ios,xcode,crash,swiftui,freeze,Ios,Xcode,Crash,Swiftui,Freeze,以下代码可以使iPhone(不是iPad)或iPhone模拟器上运行的应用程序无响应。Xcode显示应用程序在分配越来越多的内存时消耗了100%的CPU struct SecondView: View { @State private var keyboardHeight: CGFloat = 0 private let showPublisher = NotificationCenter.Publisher.init( center: .default,

以下代码可以使iPhone(不是iPad)或iPhone模拟器上运行的应用程序无响应。Xcode显示应用程序在分配越来越多的内存时消耗了100%的CPU

struct SecondView: View {
    @State private var keyboardHeight: CGFloat = 0

    private let showPublisher = NotificationCenter.Publisher.init(
        center: .default,
        name: UIResponder.keyboardWillShowNotification
    ).map { (notification) -> CGFloat in
        if let rect = notification.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? CGRect {
            return rect.size.height
        } else {
            return 0
        }
    }

    var body: some View {
        VStack(spacing: 20) {
            if keyboardHeight == 0 {
                Text("This is shown as long as there's no keyboard")
            }
            Text("This is the SecondView. Drag from the left edge to navigate back, but don't complete the gesture: crash results.")
        }.onReceive(self.showPublisher) { (height) in
            self.keyboardHeight = height
        }
        .navigationBarItems(trailing: Button("Dummy") {  })
    }
}

struct ContentView: View {
    @State var textInput = ""

    var body: some View {
        NavigationView {
            VStack(spacing: 20) {
                TextField("1. Tap here to show keyboard", text: self.$textInput)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                NavigationLink(destination: SecondView()) {
                    Text("2. Go to second screen")
                }
                Spacer()
            }
        }
    }
}
要触发冻结:

  • 轻触文本字段以显示键盘
  • 点击链接进入下一屏幕
  • 从屏幕左侧拖动,但不要完成手势,而是提前释放
  • 有一些变通办法:

    • SecondView
    • SecondView
    • 导航之前,不要在
      ContentView
      中激活键盘

    但是,我无法在我的应用程序中使用上述解决方法。有人知道根本原因是什么吗?

    在导航之前,我通过以下解决方法停用了键盘:

    NavigationLink(destination: SecondView(), tag: 2, selection: $navigationSelection) {
        EmptyView()
    }
    Text("2. Go to second screen")
        .onTapGesture {
            UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
            self.navigationSelection = 2
        }