onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
669 stars 33 forks source link

How to set popoverPresentationController sourceView in SwiftUI #894

Open onmyway133 opened 1 year ago

onmyway133 commented 1 year ago

Use a UIView as source view and set it in background

class ViewModel {
    lazy var sourceView = UIView()
}

struct SourceView: UIViewRepresentable {
    let viewModel: ViewModel

    func makeUIView(context: Context) -> UIView {
        viewModel.sourceView
    }

    func updateUIView(_ uiView: UIView, context: Context) {}
}

Button(action: {
    onShowAlert(viewModel.sourceView)
}) {
    Image(systemName: "bookmark")
}
.background(SourceView(viewModel: viewModel))

let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alertController.popoverPresentationController?.sourceView = viewModel.sourceView