Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Padding inside TextField

Tags:

I have a TextField in SwiftUI. When I apply padding to it as

TextField(text, text: $value)
    .padding()

the padding is outside of the tap area of the TextField, i.e. tapping on the padding does not bring the text field into focus.

I would like to be able to focus the TextField even if the user taps on the padding.

like image 790
Vivek Roy Avatar asked Feb 13 '21 10:02

Vivek Roy


2 Answers

You can try this. At least worked for me. Hope that helps someone:

            TextField("", text: $textfieldValueBinding)
                .frame(height: 48)
                .padding(EdgeInsets(top: 0, leading: 6, bottom: 0, trailing: 6))
                .cornerRadius(5)
                .overlay(
                    RoundedRectangle(cornerRadius: 5)
                        .stroke(lineWidth: 1.0)
                )
like image 192
Hector Rubial Avatar answered Nov 15 '22 07:11

Hector Rubial


you can check this. for now i only did with top and bottom padding. you can do the same with the leading and trailing(or with horizontal and vertical). as asked in the question this would do this "I would like to be able to focus the TextField even if the user taps on the padding."

struct ContentView: View {
@State var name = ""
@State var isTextFieldFocused = false
var body: some View {
        ZStack {
            HStack{
                Text(name)
                    .font(.system(size: 50 , weight: .black))
                    .foregroundColor(isTextFieldFocused ? Color.clear : Color.black)
                Spacer()
            }
            TextField(name, text: $name , onEditingChanged: { editingChanged in
                isTextFieldFocused = editingChanged
            }) 
            .font(.system(size: isTextFieldFocused ? 50 :  100 , weight: .black))
            .foregroundColor(isTextFieldFocused ? Color.black  : Color.clear)
            .frame(width: 300, height: isTextFieldFocused ? 50 :  100 , alignment: .center)
                        .padding(.leading, isTextFieldFocused ? 25 : 0  )
                        .padding(.trailing, isTextFieldFocused ? 25 : 0 )
            
            .padding(.top,isTextFieldFocused ? 25 : 0 )
            .padding(.bottom,isTextFieldFocused ? 25 : 0 )
            
        }.frame(width: 300)
        .background(Color.red.opacity(0.2))
}
}
like image 40
Ahmad Avatar answered Nov 15 '22 05:11

Ahmad