web-dev-qa-db-ja.com

SwiftUIで背景を透明にしてモーダルビューを作成する方法

誰もが透明な背景でモーダルビューを作成する方法を知っています。

Swiftの以下のリンクとまったく同じ

背景が透明なSwift Modal View Controller

4
user11967411

そのための理想的な方法はありませんでしたが、これを回避する方法がありました。

したがって、ビューをモーダルに表示するには、ZStackを使用して複数のビューをグループ化し、@ State変数でこのように処理します。

ここでは、説明をわかりやすくするために、ビューに背景色を指定しています。

struct ContainerView : View {

    @State var showModally = false
    var body : some View {
       ZStack {
           Group {
                Color.red.edgesIgnoringSafeArea(.all)
                VStack {
                     Button(action: {
                          self.showModally.toggle()
                      }) {
                          Text("Present Modally")
                     }
                }
           }
           ModallyPresentView(isPresented: $showModally)
               .opacity(showModally ? 1 : 0)
       }
   }
}

struct ModallyPresentView : View {

     @Binding var isPresented : Bool
     var body: some View {
       ZStack {
            Color.clear.blur(radius: 5, opaque: false)
            VStack(alignment: .center, spacing: 0) {
                Button(action: {
                   self.isPresented.toggle()
                }) {
                   Text("Dismiss")
                }
           }
           .frame(width :200,height : 200)
           .background(Color.yellow)
       }
   }
}

この場合、メインビューはコンテナービューになり、ModallyPresentViewはコンテナービューの上に表示されます。私はアニメーションの部分で働いていません。

0
Anshuman Singh

UIKitプロジェクトからSwiftUIの背景をぼかしたい場合で、モーダルビューにSwiftUIビューを使用している可能性がある場合は、最近同じ問題が発生し、UIHostController(基本的にUIViewController)を受け取るUIViewControllerを作成して、HostingControllerビューのアルファを変更します。後ろにぼかしを入れて親ビューに表示します。

ファイルを含むGistを作成して公開しました https://Gist.github.com/Ash-Bash/93fd55d89c1e36f592d3868f6b29b259

実用的な例を以下に示します。

// Initialises BlurredHostingController
var blurredHostingController = BlurredHostingController()

// Sets the Hosting View for the SwiftUI View Logic
blurredHostingController.hostingController = UIHostingController(rootView: ContentView())

// Blur Tweaks for blurredHostingController
blurredHostingController.blurEffect = .systemMaterial
blurredHostingController.translucentEffect = .ultrathin

// Presents View Controller as a Modal View Controller
self.present(blurredHostingController animated: true, completion: nil)

これがmacCatalystの結果です enter image description here

0
Ash-Bash32