Reputation: 9783
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?
Upvotes: 1
Views: 1491
Reputation: 2104
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.
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.
Upvotes: 1