SwiftUI 中是否有等效的 openSettingsURLString ?

Ale*_*Wei 5 uikit swift uialertaction swiftui

我想创建一个警报,在用户第一次拒绝使用相机后将用户重定向到设置应用程序,但到目前为止我看到的唯一方法是使用 UIKit 和

let settingsAction = UIAlertAction(title: "Settings", style: .default, handler: {action in
        UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
    })
Run Code Online (Sandbox Code Playgroud)

在 SwiftUI 中,警报中有一个操作选项,我如何才能通过 SwiftUI 的警报版本正确打开设置?

.alert(isPresented: $alertVisible) { () -> Alert in Alert (title: Text("Camera access required to take photos"), message: Text("Go to Settings?"), 
     primaryButton: .default(Text("Settings"), action: UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)), 
     secondaryButton: .default(Text("Cancel"))
Run Code Online (Sandbox Code Playgroud)

Asp*_*eri 12

这里是

.alert(isPresented: $alertVisible) {
     Alert (title: Text("Camera access required to take photos"),
            message: Text("Go to Settings?"),
            primaryButton: .default(Text("Settings"), action: {
                UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
            }),
            secondaryButton: .default(Text("Cancel")))
        }

Run Code Online (Sandbox Code Playgroud)


Vex*_*exy 12

在最短的形式中,你可以使用这样的东西:

Link("Open settings ?", destination: URL(string: UIApplication.openSettingsURLString)!)
Run Code Online (Sandbox Code Playgroud)

这将为您创建一个外观简单的按钮,直接进入“设置”应用程序。当然,您可以使用视图修饰符进一步自定义外观。


或者,如果您需要更多控制,可以openURL @Environment在视图中使用属性包装器,如下所示:

struct SomeView: View {
    @Environment(\.openURL) var openURL

    var body: some View {
        Button(action: openSettings) {
            Label("Open settings?", systemImage: "gear")
        }
    }

    private func openSettings() {
        openURL(URL(string: UIApplication.openSettingsURLString)!)
    }
}        
Run Code Online (Sandbox Code Playgroud)