Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate a Text view and its frame in SwiftUI

I can rotate the Text in SwiftUI using rotationEffect but it doesn't rotate the frame. As shown in the image, the text is rotated but the frame is still horizontal. I would like to rotate the frame too so it doesn't take up horizontal space. This is for a Mac app where I'm using HStack to prevent the Text and Circle views from overlapping when the window changes size.

vertical text

import SwiftUI

struct ContentView: View {
    var body: some View {
        HStack {
            Text("Vertical text")
                .rotationEffect(.degrees(-90))
            Circle()
        }
        .frame(width: 400, height: 300)
    }
}

One suggestion is to use ZStack. This fixes the appearance of the Text view next to the Circle but it doesn't rotate the frame of the Text view. And if ZStack is used with a resizable window then the Circle can overlap the Text view which is why I was trying to use HStack in my original example.

resizable window

struct ContentView: View {
    var body: some View {        
        ZStack(alignment: .leading) {
            Text("Vertical text")
                .rotationEffect(.degrees(-90))
            Circle()
                .padding(.leading)
        }
        .frame(minWidth: 400, minHeight: 300)
    }
}
like image 465
wigging Avatar asked Mar 07 '20 18:03

wigging


People also ask

How do I rotate text in SwiftUI?

Use any one of the . rotationEffect() methods to rotate any View clockwise, including Button and Text . Use the overloaded method with an anchor argument to rotate around a different point.

How do I rotate a view in SwiftUI?

SwiftUI's rotation3DEffect() modifier lets us rotate views in 3D space to create beautiful effects in almost no code. It accepts two parameters: what angle to rotate (in degrees or radians), plus a tuple containing the X, Y, and Z axis around which to perform the rotation.

How do I rotate an object in SwiftUI?

Go to the preview pane and select the live view button. Drag the slider to rotate the image.


1 Answers

Applying a fixedSize and frame size to the Text view appears to fix my problem. This also works well for windows that are resizable because the HStack prevents the Text view and Circle view from overlapping.

enter image description here

import SwiftUI

struct ContentView: View {
    var body: some View {
        HStack {
            Text("Vertical text")
                .rotationEffect(.degrees(-90))
                .fixedSize()
                .frame(width: 20, height: 180)
            Circle()
                .frame(width: 200)
        }
        .frame(width: 400, height: 300)
    }
}
like image 97
wigging Avatar answered Oct 05 '22 07:10

wigging