UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on 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.

2      

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 {
        content
            .padding(padding)
            .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
        }
        .padding()
    }
}

2      

@NigelGee, what about touch hit area? Padding is exluded, hit area is thin.

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED 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! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.