Damion Silver
Damion Silver

Reputation: 611

How can I center a placeholder text in a TextField

My code is as follow:

TextField("Enter Your Email", text: self.$username)

How can I make the placeholder "enter your email" be centered in the TextField?

Upvotes: 13

Views: 6504

Answers (5)

Aleš Kocur
Aleš Kocur

Reputation: 1908

I gave up on using the TextField placeholder. Instead I used ZStack to create my own view.

import SwiftUI

struct PlaceholderableTextField: View {

    @Binding var text: String
    let placeholder: String
    let axis: Axis

    @FocusState private var isFocused: Bool

    var body: some View {
        ZStack {
            if text == "" && !isFocused {
                Text(placeholder).opacity(0.5)
            }

            TextField("", text: $text, axis: axis)
                .focused($isFocused)
        }
    }
}

struct PlaceholderableTextField_Previews: PreviewProvider {
    static var previews: some View {
        PlaceholderableTextField(text: .constant("test"), placeholder: "placeholder", axis: .vertical)
    }
}

Then it's simple as

PlaceholderableTextField(text: $title, placeholder: "Enter Title", axis: .vertical)
    .multilineTextAlignment(.center)

Upvotes: 1

mohamed ayed
mohamed ayed

Reputation: 658

              TextField("Enter Your Email", text: self.$username)
                        .multilineTextAlignment(.trailing) // .center|| .leading 

Upvotes: -1

Sandeep Maurya
Sandeep Maurya

Reputation: 2099

 TextField("Enter Your Email", text: self.$username)
        .multilineTextAlignment(TextAlignment.center)

Upvotes: 25

Madhuri Doppalapudi
Madhuri Doppalapudi

Reputation: 57

let centeredParagraphStyle = NSMutableParagraphStyle()
centeredParagraphStyle.alignment = .center
let attributedPlaceholder = NSAttributedString(string: "Placeholder", attributes: [NSAttributedString.Key.paragraphStyle: centeredParagraphStyle])
textField.attributedPlaceholder = attributedPlaceholder

Upvotes: -1

Haya Hashmat
Haya Hashmat

Reputation: 137

you can use this code:

 yourtextfield.textAlignment = .center

Upvotes: 1

Related Questions