Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can you make Text in SwiftUI appear sideways while also rotating the frame?

The goal is to have something that looks like this:

Example of the desired result

I am aware of .rotationEffect(), and the solution provided here.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However the problem with this solution is that it does not rotate the frame, it only rotates the text itself.

The image below is from the Canvas preview in Xcode and the code underneath it.

Result using .rotationEffect()

HStack(spacing: 10) {
    Text("Distance")
        .rotationEffect(.degrees(270))
        .foregroundColor(.black)
        .minimumScaleFactor(0.01)

    Rectangle()
         .foregroundColor(.black)
         .frame(width: 3)
         .padding([.top, .bottom])
    Spacer()
}

As you can see, the text goes outside the frame and the frame keeps its original width, making it difficult to have the text hug the side of the view and have the vertical line hug the side of the text.

The only way I have been able to figure out how to get the desired result is to use the .offset(x:) modifier. But this feels messy and could lead to bugs down the road I think.

Is there any way to be able to rotate the frame along with the text?

I appreciate your help

>Solution :

If we talk about dynamic detection, then we need to measure text frame before rotation and apply to frame size of changed width/height

Note: of course in simplified variant frame width can be just hardcoded

enter image description here

Here is main part:

@State private var size = CGSize.zero

var body: some View {
    HStack(spacing: 10) {
        Text("Distance")
            .fixedSize()                  // << important !!
            .background(GeometryReader {
                Color.clear
                    .preference(key: ViewSizeKey.self, value: $0.frame(in: .local).size)
            })
            .onPreferenceChange(ViewSizeKey.self) {
                self.size = $0                        // << here !!
            }
            .rotationEffect(.degrees(270))
            .frame(width: size.height, height: size.width) // << here !!

Test module/dependecies on GitHub

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading