HStack 和 TextField 的角半径不更新

Corner Radius of both HStack and TextField not updating

这是我的内容视图的代码。如您所见,我已尝试使用 HStack 来包含 TextField,以及仅包含 TextField。角半径与灰色搜索矩形没有任何关系 - 边缘仍然是完美的矩形。

    
    @State var searchText = ""
    var body: some View {
        ZStack {
            //function that's the content argument to ZStack
            Color((.systemGreen))
            VStack {
                Text("App")
                    .font(.largeTitle)
                    .foregroundColor(Color.white)
                //HStack {
                TextField("Searchstring", text: $searchText)
                    .padding()
                    .background(Color(.systemGray6))
                    .padding()
                    .cornerRadius(12)
                //}
//                .padding()
//                .background(Color(.systemGray6))
//                .padding(.horizontal)
//                .cornerRadius(12)
            }
        }
    }
}

在所有情况下,预览都是这样的: corner radius fails to show in preview

问题出在这里:

.padding() /// 1.
.background(Color(.systemGray6)) /// 2.
.padding() /// 3.
.cornerRadius(12) /// 4.
  1. 您的文本字段有 padding
  2. padding 之后应用
  3. background
  4. 您在 background
  5. 之后添加另一个 padding
  6. 您在 padding
  7. 之上应用另一个 cornerRadius

因此,舍入的是 padding,而不是 background

相反,您想在 background 之后立即应用 cornerRadius

struct ContentView: View {
    @State var searchText = ""
    var body: some View {
        ZStack {
            //function that's the content argument to ZStack
            Color((.systemGreen))
            VStack {
                Text("App")
                    .font(.largeTitle)
                    .foregroundColor(Color.white)
                
                TextField("Searchstring", text: $searchText)
                    .padding()
                    .background(Color(.systemGray6))
                    .cornerRadius(12) /// corner radius immediately after the background
                    .padding() /// extra padding outside the background
            }
        }
    }
}

结果: