【问题标题】:Move TextEditor (in List) up when the keyboard appeared in SwiftUI当键盘出现在 SwiftUI 中时,向上移动文本编辑器(在列表中)
【发布时间】:2021-12-30 05:23:11
【问题描述】:

我有一个 SwiftUI List,最后一行是 TextEditor。在 SwiftUI 中,文本字段会自动向上移动到键盘上方。但不幸的是,当 TextEditor 在 List 中时,它似乎不起作用。

在使用TextField 时有很多很好的解决方案,例如:-Move TextField up when the keyboard has appeared in SwiftUI。但是在使用TextEditor 时,它们似乎都不起作用。


struct ContentView: View {

    @State var items: [String] = ["Apples", "Oranges", "Bananas", "Pears", "Mangos", "Grapefruit","Apples", "Oranges", "Bananas", "Pears", "Mangos", "Grapefruit"]

    @State private var newItemText : String = ""


    var body: some View {
        ZStack(alignment: Alignment.bottom) {
            List{
                 ForEach(items, id: \.self) { 
                     Text("\($0)")
                 }
                 TextEditor(text: $newItemText)
            }
            
        }
    }
}

【问题讨论】:

  • 您需要将ZStack 向上移动,而不仅仅是TextEditor。考虑到这一点,尝试其他解决方案。
  • 试过了,好像没用。这对你有用吗?
  • 我没有完成答案,这就是我没有发布它的原因。所以,你是说你在你的ZStack 上加上一个.frame 和一个GeometryReader,然后将ZStack 的高度减少了键盘的高度,它没有缩小?
  • 它确实缩小了ZStack 的高度,但列表不会滚动到底部,所以最后一项仍然不可见。
  • 你从来没有告诉列表这样做。随着键盘的出现,这不是自动的。搜索scrollTo

标签: swift swiftui swiftui-list swiftui-texteditor


【解决方案1】:

似乎视图会自动调整大小,使其位于键盘上方。所需要做的就是滚动到列表的最后一行。

struct ContentView: View {

    @State var items: [String] = ["Apples", "Oranges", "Bananas", "Pears", "Mangos", "Grapefruit","Apples", "Oranges", "Bananas", "Pears", "Mangos", "Grapefruit"]

    @State private var newItemText : String = ""


    var body: some View {
      ScrollViewReader { (proxy: ScrollViewProxy) in
        ZStack(alignment: Alignment.bottom) {
            List{
                 ForEach(items, id: \.self) { 
                     Text("\($0)")
                 }
                 TextEditor(text: $newItemText)
                    .onChange(of: newItemText) { newValue in
                          proxy.scrollTo(999, anchor: .bottom)
                   }.id(999)
            }
            
        }
      }
    }
}

【讨论】:

    猜你喜欢
    • 2019-10-22
    • 2014-12-26
    • 2020-05-21
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    相关资源
    最近更新 更多