How to rotate a view
About 2 min
How to rotate a view êŽë š
SwiftUI by Example
Back to Home
How to rotate a view | SwiftUI by Example
How to rotate a view
Updated for Xcode 15
SwiftUIâs rotationEffect()
modifier lets us rotate views freely, using either degrees or radians.
For example, if you wanted to rotate some text by -90 degrees so that it reads upwards, you would use this:
Text("Up we go")
.rotationEffect(.degrees(-90))
If you prefer using radians, just pass in .radians()
as your parameter, like this:
Text("Up we go")
.rotationEffect(.radians(.pi))
View rotation is so fast that itâs effectively free, so you could even make it interactive using a slider if you wanted:
struct ContentView: View {
@State private var rotation = 0.0
var body: some View {
VStack {
Slider(value: $rotation, in: 0...360)
Text("Up we go")
.rotationEffect(.degrees(rotation))
}
}
}
By default views rotate around their center, but if you want to pin the rotation from a particular point you can add an extra parameter for that. For example if you wanted to make the slider above pivoting the rotation around the viewâs top-left corner youâd write this:
struct ContentView: View {
@State private var rotation = 0.0
var body: some View {
VStack {
Slider(value: $rotation, in: 0...360)
Text("Up we go")
.rotationEffect(.degrees(rotation), anchor: .topLeading)
}
}
}
Similar solutionsâŠ
How to rotate a view in 3D | SwiftUI by Example
How to rotate a view in 3D
SwiftUI tips and tricks | SwiftUI by Example
SwiftUI tips and tricks
How to convert a SwiftUI view to an image | SwiftUI by Example
How to convert a SwiftUI view to an image
How to make a view dismiss itself | SwiftUI by Example
How to make a view dismiss itself
How to create and compose custom views | SwiftUI by Example
How to create and compose custom views