簡體   English   中英

SwiftUI 文本編輯器滾動顯示鍵盤不起作用

[英]SwiftUI TextEditor Scroll with Show Keyboard Not Working

我有一個帶有 SwiftUI 生命周期的 SwiftUI 應用程序,它使用 TextFields 和 TextEditors。 我編寫了一個修飾符來處理在鍵盤存在時滾動鍵盤下方的內容。 我的修飾符對於 TextFields 可以正常工作,但對於 TextEditors 則完全不同。 Apple 文檔說,keyboardWillShowNotification 是在鍵盤顯示之前立即發布的。 我找不到任何聲明通知僅限於 TextFields 的內容。 兩種字段類型都在同一個 ScrollView 中。 希望我在這里遺漏了一些簡單的東西。

我的修改器:

struct AdaptsToSoftwareKeyboard: ViewModifier {

    @State var currentHeight: CGFloat = 0

    func body(content: Content) -> some View {
        content
            .padding(.bottom, self.currentHeight)
            .edgesIgnoringSafeArea(self.currentHeight == 0 ? Edge.Set() : .bottom)
            .onAppear(perform: subscribeToKeyboardEvents)
    }

    private let keyboardWillOpen = NotificationCenter.default
        .publisher(for: UIResponder.keyboardWillShowNotification)
        .map { $0.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect }
        .map { $0.height }

    private let keyboardWillHide =  NotificationCenter.default
        .publisher(for: UIResponder.keyboardWillHideNotification)
        .map { _ in CGFloat.zero }

    private func subscribeToKeyboardEvents() {
        _ = Publishers.Merge(keyboardWillOpen, keyboardWillHide)
            .subscribe(on: RunLoop.main)
            .assign(to: \.self.currentHeight, on: self)
    }
}

任何指導將不勝感激。 Xcode 12.2 測試版 (12B5018i) iOS 14

第一次編輯:我認為問題可能是在 TextEditor 獲得焦點時無法收到通知。 但是,將此修飾符添加到 TextEditor 顯示通知已觸發。 沒有進展:

   .onReceive(NotificationCenter.default.publisher(for: UIApplication.keyboardWillShowNotification)) { _ in
        print("Cursor is in TextEditor!")
    }

我假設你應該存儲訂閱者如下

struct AdaptsToSoftwareKeyboard: ViewModifier {

    @State var currentHeight: CGFloat = 0
    @State private var cancelable: AnyCancellable?
    
    func body(content: Content) -> some View {
        content
            .padding(.bottom, self.currentHeight)
            .edgesIgnoringSafeArea(self.currentHeight == 0 ? Edge.Set() : .bottom)
            .onAppear(perform: subscribeToKeyboardEvents)
    }

    private let keyboardWillOpen = NotificationCenter.default
        .publisher(for: UIResponder.keyboardWillShowNotification)
        .map { $0.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect }
        .map { $0.height }

    private let keyboardWillHide =  NotificationCenter.default
        .publisher(for: UIResponder.keyboardWillHideNotification)
        .map { _ in CGFloat.zero }

    private func subscribeToKeyboardEvents() {
        self.cancelable = Publishers.Merge(keyboardWillOpen, keyboardWillHide)
            .subscribe(on: RunLoop.main)
            .assign(to: \.self.currentHeight, on: self)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM