NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

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 Stream

SPONSORED Check out Stream's cross-platform open source chat SDK on GitHub! Write once and deploy your app with fully featured chat UI on iOS and macOS.

Go to GitHub

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.