2

如您所见,我想将搜索栏完全放在顶部,safeAreaproxy.safeAreaInsets由于PreviewProvider父级使用edgesIgnoringSafeArea.

我能做些什么 ?有什么方法可以访问 safeAreaInsets?

struct FindView: View {
  
  // MARK: -  Properties
  @ObservedObject var viewModel: FindViewModel
  
  init(viewModel: FindViewModel){
    self.viewModel = viewModel

  }
  
  var body: some View {
 
      GeometryReader { proxy in
        ScrollView(.vertical, showsIndicators: true, content: {
          VStack(alignment: .leading, spacing: 8){
             SearchBar()
              .frame(height: 48, alignment: .center)
              .padding(.all, 16)
              
            
            Text("Categories")
              .multilineTextAlignment(.leading)
              .font(.system(size: 21))
              .padding(.all, 16)
              
          }.frame(width: proxy.size.width)
        })
      }
  }
}

struct FindView_Previews: PreviewProvider {
  static var previews: some View {
    ZStack(alignment: .center, content: {
      Rectangle().foregroundColor(.red)
      FindView(viewModel: FindViewModel())
    }).edgesIgnoringSafeArea(.all)
  }
}

代码预览

4

2 回答 2

1

简单的方法;

     struct test: View {
          var body: some View {
              VStack{
                Text("Your view comes here")
                Spacer()
              }
               .frame(minWidth:0, maxWidth: .infinity, minHeight: 0,maxHeight: .infinity, alignment: .center)
               .padding(.top,UIApplication.shared.windows.first?.safeAreaInsets.top ?? 40)
               .background(Color.red)
               .edgesIgnoringSafeArea(.all)
          }
      }
于 2020-09-26T18:32:39.520 回答
0

您应该将.edgesIgnoringSafeArea(.all)only 应用于矩形,而不是 ZStack。这样,只有它应该填满屏幕,而其他一切都保持原位。

然后,要使其FindView填充屏幕(尊重安全区域),您需要使其框架扩展为.frame(maxWidth: .infinity, maxHeight: .infinity)


代码示例:

struct ContentView: View {
    var body: some View {
        ZStack {
            Rectangle()
                .fill(Color.red)
                .edgesIgnoringSafeArea(.all)
            Text("This should respect the safe area")
                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
        }
    }
}
于 2020-09-26T16:16:11.547 回答