extension UIViewController {
class func getCurrentVC() -> UIViewController? {
var result: UIViewController?
var window = UIApplication.shared.windows.first { $0.isKeyWindow }
if window?.windowLevel != UIWindow.Level.normal {
let windows = UIApplication.shared.windows
for tmpWin in windows {
if tmpWin.windowLevel == UIWindow.Level.normal {
window = tmpWin
break
}
}
}
let fromView = window?.subviews[0]
if let nextRespnder = fromView?.next {
if nextRespnder.isKind(of: UIViewController.self) {
result = nextRespnder as? UIViewController
result?.navigationController?.pushViewController(result!, animated: false)
} else {
result = window?.rootViewController
}
}
return result
}
}
func showMyAlert() {
let myAlert = UIAlertController(title: "Confirm order", message: "Are you sure to order two box of chocolate?", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok!", style: .default) { (_) in
print("You just confirm your order")
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in
print(You cancel it already!)
}
myAlert.addAction(okAction)
myAlert.addAction(cancelAction)
myAlert.presentAlert()
}
var body: some View {
Button(action:{
NotificationCenter.default.post(name: Notification.Name("showAlert"), object: "Ελέγξτε το δίκτυο σας και προσπαθήστε αργότερα.")
}
}
4条答案
按热度按时间qcbq4gxm1#
这只是工作:
字符串
把它放在一个助手类。
使用方法:
型
9jyewag02#
使用
Alert
代替。字符串
绑定到
isPresented
以控制演示文稿。更新:
正如James Toomey在评论中提到的,有一个更好的方法:
alert(_:isPresented:presenting:actions:message:)
官方文档:https://developer.apple.com/documentation/swiftui/view/alert(_:ispresented:presenting:actions:message:)-8584l
eni9jsuy3#
我正在使用UIViewController的扩展来获取当前的vc和UIAlertController来呈现'Alert'。也许你可以尝试如下:
UIViewController的扩展
字符串
UIAlertController的扩展
型
现在您可以创建showAlert函数了
型
希望我的回答能帮到你:-)
zf2sa74q4#
您可以使用notificationCenter在SwiftUI中呈现UIKit警报
在SceneDelegate.swift on“func scene(_ scene:UIScene,willConnectTo session:UISceneSession,options connectionOptions:UIScene.ConnectionOptions)”插入以下代码{
字符串
并添加此功能
型
现在,您可以使用UIKit AlertController在swifui类中的操作上编写此代码,使应用程序显示消息
型