如何解决显示不涉及ContentView的SwiftUI AlertDialog
iOS和Swift全新。现在,SwiftUI出现了。使用UIKit,当我的蓝牙代码发现新设备时,我弹出一个对话框。在蓝牙代码中,我在主线程上使用了DispatchQueue来调用委托方法。在处理该委托调用的类中,我创建了一个UIAlertController,并在对话框字段中填充了有关该设备的信息,并询问“是否要连接到该设备?”如果用户单击“是”按钮,我将在蓝牙代码中调用一个方法进行连接。
令人高兴的是,整个过程是通过处理发现事件的方法完成的。现在,SwiftUI出现了,我不知道该怎么做。看来我需要涉及ContentView并使用绑定方法来发出警报的信号。然后我必须弄清楚当用户单击“是”时如何调用正确的方法。
如何在委托方法处理程序中处理整个过程,并避免使用ContentView(不使用UIKit)。
这是我的UIKit UIAlertController实现:
// Delegate function to receive discovery events
func discoveredDevice(device: CBPeripheral,uuid: CBUUID)
{
let alert = UIAlertController(title: "Device discovered",message: Btle().getDeviceType(uuid: uuid),preferredStyle: .alert)
alert.addTextField {
(name: UITextField) in
name.text = device.name != nil ? "Name: \(device.name!)" : "Name: No name provided"
name.isUserInteractionEnabled = false
}
alert.addTextField {
(address: UITextField) in
address.text = "Do you want to Connect to this Device?"
address.isUserInteractionEnabled = false
}
alert.addAction(UIAlertAction(title: "YES",style: .default,handler: {
[weak alert] (_) in
self.btleManager.connectFromDiscovery(device: device)
}))
alert.addAction(UIAlertAction(title: "NO",handler: {
[weak alert] (_) in
}))
self.present(alert,animated: true,completion: nil)
}
请注意,整个警报是通过一种方法处理的,包括用户的响应。
现在使用SwiftUI,我已经走到了这一步
// Delegate function to receive discovery events
func discoveredDevice(device: CBPeripheral,uuid: CBUUID)
{
var alert = Alert(title: Text("Device discovered"),message: Text(Btle().getDeviceType(uuid: uuid)),primaryButton: Alert.Button.default(Text("YES"),action: {self.btleManager!.connectFromDiscovery(device: device)}),secondaryButton: Alert.Button.cancel(Text("NO")))
}
但是我不知道如何在此方法中显示它。如果提供了与UIAlertController一起提供的额外TextView,那将是很好的选择,但这只是在现阶段锦上添花。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。