HStack 和 TextField 的角半径未更新

ani*_*an9 2 swift swiftui contentview

这是我的内容视图的代码。正如您所看到的,我尝试了使用 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)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在所有情况下,预览都是这样的: 角半径无法在预览中显示

ahe*_*eze 20

问题就在这里:

.padding() /// 1.
.background(Color(.systemGray6)) /// 2.
.padding() /// 3.
.cornerRadius(12) /// 4.
Run Code Online (Sandbox Code Playgroud)
  1. 您的文本字段有一个padding
  2. background被应用,之后padding
  3. padding在之后添加另一个background
  4. cornerRadius在上面应用另一个padding

结果,padding四舍五入的是 ,而不是background

显示圆形透明填充的图表

相反,您希望cornerRadius立即应用background.

显示圆形背景,然后在外部填充的图表

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
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

背景是圆形的,然后在外部应用内边距