【发布时间】:2020-04-04 04:00:29
【问题描述】:
我正在开发一个蓝牙应用程序。它有引导和仪表板。在引导上有配对和如何使用模块的说明,仪表板控制外围设备。所以我需要使用警报和将其导航到名为 Onboarding 的不同页面。如何使用警报导航到不同的视图。
代码块
import SwiftUI
import BLE
struct Dashboard: View {
@EnvironmentObject var BLE: BLE
@State private var showUnpairAlert: Bool = false
@State private var hasConnected: Bool = false
let defaults = UserDefaults.standard
let defaultDeviceinformation = "01FFFFFFFFFF"
struct Keys {
static let deviceInformation = "deviceInformation"
}
var body: some View {
VStack(alignment: .center, spacing: 0) {
// MARK: - Menu Bar
HStack(alignment: .center, spacing: 10) {
VStack(alignment: .center, spacing: 4) {
Text(self.hasConnected ? "PodId \(checkForDeviceInformation())":"Pod is not connected")
.font(.footnote)
.foregroundColor(.white)
Button(action: {
print("Unpair tapped!")
self.showUnpairAlert = true
}) {
HStack {
Text("Unpair")
.fontWeight(.bold)
.font(.body)
}
.frame(minWidth: 85, minHeight: 35)
.foregroundColor(.white)
.background(Color(red: 0.8784313725490196, green: 0.34509803921568627, blue: 0.36470588235294116))
.cornerRadius(30)
}
}
}
}
.alert(isPresented: $showUnpairAlert) {
Alert(title: Text("Unpair from \(checkForDeviceInformation())"), message: Text("Do you want to unpair the current pod?"), primaryButton: .destructive(Text("Unpair")) {
self.unpairAndSetDefaultDeviceInformation()
}, secondaryButton: .cancel())
}
}
func checkForDeviceInformation() -> String {
let deviceInformation = defaults.value(forKey: Keys.deviceInformation) as? String ?? ""
print("Device Info \(deviceInformation)")
return deviceInformation
}
func unpairAndSetDefaultDeviceInformation() {
defaults.set(defaultDeviceinformation, forKey: Keys.deviceInformation)
print("Pod unpaired and view changed to Onboarding")
}
}
谢谢!!!!
【问题讨论】:
-
是的@sugar2code 我尝试使用演示模式,但这只是为了关闭我想要导航到不同视图的视图
-
哦,我明白了!我认为这篇文章很相似:stackoverflow.com/questions/57645518/…。他们会发出警报以检查错误,然后在一切正常时进行导航。所以你需要调整按钮动作,但我认为原理是一样的,你的主视图中有一个导航链接,如果某些环境变量为真,则可见,然后通过警报按钮切换该状态。希望这会有所帮助!
-
感谢@sugar2code 的解决方案:)
-
嘿@sugar2code 我有一个问题当我实现代码时,视图由于某种原因向上移动。你有什么想法吗?我将它导航到旧视图。
标签: swift swiftui swift5.1 swiftui-navigationlink