1

I have a LazyVStack in my UI and after device rotation the rows showing are not the same as prior to rotation. Not even close to those rows.

Prior to SwiftUI I was handling this by getting the last visible row in viewWillTransition and then scrolling to it after the orientationDidChangeNotification.

I have not found any way in SwiftUI of detecting when the device will change so that I can get the last row index and scroll to it after rotation.

Is there any equivalent of viewWillTransition or any strategy I can employ to get that functionality?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
alionthego
  • 8,508
  • 9
  • 52
  • 125

1 Answers1

1

To be notified of rotation changes in SwiftUI, you can do:

struct ContentView: View {
    let rotationChangePublisher = NotificationCenter.default
        .publisher(for: UIDevice.orientationDidChangeNotification)
    
    var body: some View {
        Text("Some View !")
            .onReceive(rotationChangePublisher) { _ in
                print("View Did Rotate")
            }
    }
}

To be able to scroll to any row you want at your will, you should read this amazing blog post by Majid: https://swiftwithmajid.com/2020/09/24/mastering-scrollview-in-swiftui/
This is one of the only ways to do what you want in SwiftUI, and i'd say the best way, although its a bit hacky.

EDIT 1:

To be able to scroll to the last row of before the rotation, you need to store the recent last visible rows in a array or something similar, alongside the orientation. Then whenever device changed its orientation you can pick the last value from the array which has the previous orientation, and scroll to that row.

Mahdi BM
  • 1,826
  • 13
  • 16
  • thanks but as I mentioned in the question I don't need to know after the device has rotated. I need to know just before rotation. Thus the reference to viewWillTransition. I need the index just before transition so after the rotation I know which row to scroll to because it will already do a random scroll during the rotation as it tries to figure out the dynamic row heights. – alionthego Apr 12 '21 at 12:23
  • Hmmmm, i understand. Then from what i can tell, you need to store the recent last visible rows in a array alongside the orientation. Then whenever device changed its orientation you can pick the last value from the array which has the previous orientation, and scroll to that row. – Mahdi BM Apr 12 '21 at 12:35