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.
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.
struct ContentView: View {
var body: some View {
ZStack(alignment: .leading) {
Text("Vertical text")
.rotationEffect(.degrees(-90))
Circle()
.padding(.leading)
}
.frame(minWidth: 400, minHeight: 300)
}
}
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.
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.
Go to the preview pane and select the live view button. Drag the slider to rotate the image.
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.
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With