Let me know if this is a duplicate question.
I am developing an app with a photo picker. I am on view A and there is a + button on it. When I tap on the +, I want to navigate to a view B. Upon navigation I want to present a Photo Picker view automatically inside view B. I am not able to figure out how to do that presentation of the sheet in Swiftui.
In UIKit,on the viewdidappear of viewcontroller B, i would present the Pickerview.
Here’s the code that I have
```import SwiftUI
struct ViewB: View {
@State private var showingImagePicker = false
@State private var uploadedPhotos = [UIImage]()
var body: some View {
VStack {
Button("Select Image") {
showingImagePicker = true
}
}
.sheet(isPresented: $showingImagePicker) {
PhotoPicker(photoList: $uploadedPhotos)
}
.onChange(of: uploadedPhotos) { _ in
}
}
}```
This code is ViewB and I will present the pickerView on tapping a button in viewB. but I don’t want to tap on button but instead want the picker to show up on appear of ViewB
2
Answers
Think I figured it out -
Here PhotoPicker() is the customview that I have
There is a view modifier in SwiftUI known as
.onAppear(perform:)
, which is the SwiftUI counterpart to UIKit’sviewDidAppear
and gives you an entry point upon the construction and display of a SwiftUI view. Simply add this modifier to View B (the view inside the sheet that you are presenting). In the closure that you provide to the modifier, you can change the state to present the picker as needed.If you’d like the picker view to animate in after the view appears, the appropriate place to declare the transition and animation context is on the view acting as your picker view.
Read more about the modifier here:
https://developer.apple.com/documentation/SwiftUI/AnyView/onAppear(perform🙂