How do I create a view in an iOS app that doesn’t rotate while its parent view does rotate as the device rotates

Asked on 07/31/2024

1 search

To create a view in an iOS app that doesn’t rotate while its parent view does rotate as the device rotates, you can use SwiftUI's view modifiers to control the rotation behavior. Specifically, you can apply a rotation effect to the child view that counteracts the rotation of the parent view.

Here's a basic example of how you might achieve this:

import SwiftUI

struct ContentView: View {
    @State private var rotationAngle: Angle = .zero

    var body: some View {
        GeometryReader { geometry in
            ZStack {
                // Parent view that rotates
                Color.blue
                    .edgesIgnoringSafeArea(.all)
                    .rotationEffect(rotationAngle)
                    .onAppear {
                        // Simulate device rotation
                        withAnimation(.linear(duration: 2).repeatForever(autoreverses: false)) {
                            rotationAngle = .degrees(360)
                        }
                    }

                // Child view that counteracts the rotation
                Text("Fixed View")
                    .font(.largeTitle)
                    .foregroundColor(.white)
                    .rotationEffect(-rotationAngle)
            }
        }
    }
}

In this example:

  • The parent view (a blue background) rotates continuously.
  • The child view (a text label) applies a rotation effect that is the negative of the parent view's rotation, effectively canceling out the rotation and keeping the text label fixed.

For more advanced control and customization, you can explore the capabilities of SwiftUI and UIKit as discussed in the SwiftUI essentials session at WWDC 2024. This session covers various built-in capabilities and low-level APIs that can help you create unique custom experiences in your app.