FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

TextField margin

Forums > SwiftUI

Is it possible to set a margin for a TextField where the text has a uniform space (say 3px) between the text and the border?

Not thinking about .padding() as that puts space outside between the TextField (outside it's border) and other components.

Not a huge thing, but would be a nice to have styling thing.


Hi TheTwoNotes

If you make a file with this in

import SwiftUI

struct TextFieldModifier: ViewModifier {
    let color: Color
    let padding: CGFloat // <- space between text and border
    let lineWidth: CGFloat

    func body(content: Content) -> some View {
            .overlay(RoundedRectangle(cornerRadius: padding)
                        .stroke(color, lineWidth: lineWidth)

extension View {
    func customTextField(color: Color = .secondary, padding: CGFloat = 3, lineWidth: CGFloat = 1.0) -> some View { // <- Default settings
        self.modifier(TextFieldModifier(color: color, padding: padding, lineWidth: lineWidth))

As you can see the modifier has defaults which you can change then anywhere you want a TextField with the same or you can change is as below

struct ContentView: View {
    @State private var amount = ""

    var body: some View {
        VStack {
            TextField("Enter Amount", text: $amount)
                .customTextField() // Using defaults

            TextField("Enter Amount", text: $amount)
                .customTextField(padding: 10) // change the amount space between text and border

            TextField("Enter Amount", text: $amount)
                .customTextField(color: .blue, padding: 10, lineWidth: 2) // change color and thickness of line


Hacking with Swift is sponsored by Essential Developer

SPONSORED From August 2nd to 8th you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!

Save your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.