SwiftUI:当列表过长时,SearchBar越界

问题描述

我已经在自定义标题中的应用中实现了搜索栏。在搜索栏下方,我添加一个错误List,该行有100行,用于显示搜索结果

我面临的问题是:

接下来的两个主题不合时宜。

  • 键盘在屏幕上时,列表的最后几行不可见。如何解决Link to video 2
  • 如何为List设置背景颜色?我还没弄清楚。 (listRowBackground修饰符无法按照我阅读的文章的建议使用。)

我正在使用Xcode 12.0 beta 6。

let screen = UIScreen.main.bounds

struct SearchBarView: View {
    @Binding var search: String
    @Binding var searchSelected: Bool
    
    var body: some View {
        vstack {
            CustomTextField(text: $search,isFirstResponder: true)
                .modifier(SearchBarTextFieldStyle(search: $search))

            if !search.isEmpty {
                  List(1..<100) { i in
                      Text("Hello \(i)")
                  }.frame(width: screen.width)
            }
        }
        .frame(width: screen.width,height: !search.isEmpty ? screen.height : 40)
        .background(Color("ThemeColor"))
    }
}

解决方法

出现列表时,搜索栏会移出边界。当我添加 顶部填充为400像素,搜索栏就会回到边界。

问题在于所有内容都放在一个VStack中。因此,当搜索不再为空时,TextFieldList共享为其提供的空间。

TextField放在这样的单独堆栈中:

struct ContentView: View {
    
    @State var search: String = ""
    
    var body: some View {
        // Everything wrapped in one Stack
        VStack() {
            
            // Separate Stack for the TextField 
            HStack() {
                TextField("Title",text: self.$search)
            }.padding()
            
            // One Stack for the content
            VStack {
                if !search.isEmpty {
                      List(1..<100) { i in
                          Text("Hello \(i)")
                      }.frame(width: UIScreen.main.bounds.width)
                }
            }.frame(width: UIScreen.main.bounds.width)
                .background(Color.red)
            
            Spacer() // So that the TextField is also on top when no content is displayed 
        }
    }
}

当键盘在屏幕上时,列表的最后几行不会 可见。如何解决?

在列表的底部添加一个填充,但我建议实施以下解决方案:Move TextField up when the keyboard has appeared in SwiftUI

例如带有填充:

import SwiftUI

struct ContentView: View {
    
    @State var search: String = ""
    
    var body: some View {
        VStack() {
            
            HStack() {
                TextField("Title",text: self.$search)
            }.padding()
            
            VStack {
                if !search.isEmpty {
                    List(1..<100) { i in
                        Text("Hello \(i)")
                    }.frame(width: UIScreen.main.bounds.width)
                        .padding(.bottom,300) // here padding
                }
            }.frame(width: UIScreen.main.bounds.width)
                
            
            Spacer()
        }
    }
}

如何为列表设置背景色?我没能 弄清楚。 (listRowBackground修饰符无法像 我读过的一篇文章建议)。

这个问题也已经在这里得到回答: SwiftUI List color background