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
?
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
?
TextField("Enter Your Email", text: self.$username)
.multilineTextAlignment(TextAlignment.center)
you can use this code:
yourtextfield.textAlignment = .center
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)
.multilineTextAlignment((text.isEmpty && !isFocused) ? .center : .leading)
–
Crossbred let centeredParagraphStyle = NSMutableParagraphStyle()
centeredParagraphStyle.alignment = .center
let attributedPlaceholder = NSAttributedString(string: "Placeholder", attributes: [NSAttributedString.Key.paragraphStyle: centeredParagraphStyle])
textField.attributedPlaceholder = attributedPlaceholder
TextField("Enter Your Email", text: self.$username)
.multilineTextAlignment(.trailing) // .center|| .leading
© 2022 - 2024 — McMap. All rights reserved.