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?

Answered by coffeecoder in 371549022

Just found it! 🙂

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

By the way all textfields are multiline by default.

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.

Accepted Answer

Just found it! 🙂

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

By the way all textfields are multiline by default.

20

Anyone knows how to center the text vertically?

text alignment in SwiftUI
 
 
Q