SwiftUI 中的文本编辑器被键盘遮挡

Ser*_*gey 6 ios swiftui

我希望我的文本编辑器避免使用屏幕键盘,这样我就可以输入一些内容并看到它:)我想我可以以 iOS 15 为目标。我相信我在互联网上尝试了许多处理键盘事件的解决方案并尝试调整一些填充/偏移等,但它们都不适合我。看起来像文本字段根本没有这个问题(至少在 iOS 15 中),因为即使键盘出现在屏幕上,它们也保持可见(容器视图根据需要滚动)。我不知道为什么这个基本功能不是免费提供的... UIKit/UITextView 似乎无需开发人员额外的照顾即可工作。

那么,我需要做什么才能在下面的示例中进入第三个文本编辑器(在“注释”部分中)并立即开始输入,而无需手动滚动视图以使编辑器对我可见?

import SwiftUI

struct ContentView: View {
    @State private var text: String = ""
    
    init() {
        UITextView.appearance().backgroundColor = .clear
    }
    
    var body: some View {
        Form {
            TextEditor(text: $text)
                .frame(height: 300)
                .background(.yellow)
            TextEditor(text: $text)
                .frame(height: 300)
                .background(.mint)
            Section("Notes") {
                TextEditor(text: $text)
                    .frame(height: 300)
                    .background(.teal)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Run Code Online (Sandbox Code Playgroud)

Asp*_*eri 7

TextEditor 本身就是滚动视图,因此操作系统可能会混淆什么/在哪里移动/偏移...无论如何,在这种情况下的一种可能的方法(或者为什么你将所有这些编辑器包装在 ForEach 中)是使用可聚焦状态并强制所有内容向上明确地。

使用 Xcode 13.4 / iOS 15.5 进行测试

演示

这是主要部分:

        TextEditor(text: $text).id(2)
            .focused($inFocus, equals: 2)
            .frame(height: 300)
            .background(.teal)
        
        if inFocus == 2 {
            Color.clear.frame(height: 300)
        }
    }
    .onChange(of: inFocus) { id in
        withAnimation {
            sp.scrollTo(id)
        }
    }
Run Code Online (Sandbox Code Playgroud)

完整的测试代码在这里