13

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Damion Silver
  • 491
  • 1
  • 4
  • 16

5 Answers5

23
 TextField("Enter Your Email", text: self.$username)
        .multilineTextAlignment(TextAlignment.center)
Sandeep Maurya
  • 1,979
  • 17
  • 22
1

you can use this code:

 yourtextfield.textAlignment = .center
Haya Hashmat
  • 137
  • 10
1

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)
Aleš Oskar Kocur
  • 1,381
  • 1
  • 13
  • 29
-1
let centeredParagraphStyle = NSMutableParagraphStyle()
centeredParagraphStyle.alignment = .center
let attributedPlaceholder = NSAttributedString(string: "Placeholder", attributes: [NSAttributedString.Key.paragraphStyle: centeredParagraphStyle])
textField.attributedPlaceholder = attributedPlaceholder
-1
              TextField("Enter Your Email", text: self.$username)
                        .multilineTextAlignment(.trailing) // .center|| .leading 
moahmed ayed
  • 636
  • 7
  • 10