text alignment in SwiftUI

I would like to center align the text inside a TextField. I just couldn't find a way to do it. I know in UIKit you could do


mytext.textAlignment = .right


Could anyone post the equivenant of this in SwiftUI please?

Accepted Reply

Just found it! 🙂

It is .multilineTextAlignment(.center) on the textfield.

By the way all textfields are multiline by default.

  • Sorry but anyone find out a way to justify a Text in Swiftui?

Add a Comment

Replies

Alignment values seem are passed down the view heirarchy, so you could try wrapping your TextField in a frame with the alignment modifier set. Though, to be brutally honest, I think TextFields as of Beta 3 are highly unpolished in general (I've been wrapping a UIKit component in lieu of using TextField).

Thanks m_bedwell


I tried wrapping it in a frame with the alignment modifier but that doesn't work. I have a feeling that the alignment modifier only works with the alignment of the childviews themselves within the container. The alignment of text within a view (such as a Textfield) might be specified by a different modifier specific to textField. For example, you may want to center align a textfield within it's parent container, but inside the textField you may want to align the text to the leading edge. I feel there should be two independent modifiers , one for aligning the view and the other for text.


But as you say Beta3 is still quite unpolished so we will get the answers later on I guess.

Just found it! 🙂

It is .multilineTextAlignment(.center) on the textfield.

By the way all textfields are multiline by default.

  • Sorry but anyone find out a way to justify a Text in Swiftui?

Add a Comment

Anyone knows how to center the text vertically?