Search code examples
swiftswiftuicontentview

Corner Radius of both HStack and TextField not updating


This is the code for my content view. As you can see, I've tried both an HStack to contain the TextField, as well as just the TextField on its own. The corner radius doesn't have any bearing on the grey search rectangle - the edges are still perfectly rectangular.

    
    @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)
            }
        }
    }
}

And this is what the preview looks like, in all cases: corner radius fails to show in preview


Solution

  • The problem is here:

    .padding() /// 1.
    .background(Color(.systemGray6)) /// 2.
    .padding() /// 3.
    .cornerRadius(12) /// 4.
    
    1. Your text field has a padding
    2. background gets applied, after the padding
    3. You add another padding, after the background
    4. You apply another cornerRadius on top of padding

    As a result, it's the padding that gets rounded, not the background.

    Diagram showing transparent padding rounded

    Instead, you want to apply the cornerRadius immediately after the background.

    Diagram showing background rounded, then padding on outside

    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
                }
            }
        }
    }
    

    Result:

    Background is rounded, then padding applied outside