How can I center a placeholder text in a TextField
Asked Answered
S

5

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?

Stantonstanway answered 3/12, 2019 at 6:50 Comment(0)
A
24
 TextField("Enter Your Email", text: self.$username)
        .multilineTextAlignment(TextAlignment.center)
Amby answered 3/12, 2019 at 7:23 Comment(1)
This will center the text but it won't center the placeholder.Cohin
L
1

you can use this code:

 yourtextfield.textAlignment = .center
Lien answered 3/12, 2019 at 6:57 Comment(1)
This is not SwiftUIClaudette
D
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)
Diplostemonous answered 21/6, 2023 at 12:38 Comment(1)
You could accomplish the same by using .multilineTextAlignment((text.isEmpty && !isFocused) ? .center : .leading)Crossbred
C
-1
let centeredParagraphStyle = NSMutableParagraphStyle()
centeredParagraphStyle.alignment = .center
let attributedPlaceholder = NSAttributedString(string: "Placeholder", attributes: [NSAttributedString.Key.paragraphStyle: centeredParagraphStyle])
textField.attributedPlaceholder = attributedPlaceholder
Cobham answered 3/12, 2019 at 7:1 Comment(0)
H
-1
              TextField("Enter Your Email", text: self.$username)
                        .multilineTextAlignment(.trailing) // .center|| .leading 
Homoeroticism answered 17/3, 2021 at 14:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.