gpt4 book ai didi

ios - Swift:从实用程序类调用 UIAlertController

转载 作者:行者123 更新时间:2023-11-30 12:33:55 25 4
gpt4 key购买 nike

作为一名 Swift 开发人员,我目前正在尝试更多地学习和提高我的技能,这可能会被认为是一个愚蠢的问题,但我很好奇。

问题
在我的代码中,我不断重复 UIAlertController 创建和演示代码,以至于看起来很草率。此外,将其分派(dispatch)到主线程最多需要 5 行,并且我在整个项目中在多个 View Controller 上多次重复此代码。因此,我创建了一个“实用程序”类,在该类中我有一个显示 UIAlertController 的函数。

问题
我想知道的是,这是不好的编码习惯吗?不断地从另一个类调用这个函数,不断地创建一个新的 UIAlertController 是不是很草率?这会减慢我的申请完成速度吗?或者这完全没问题吗?

重要的代码:

class Utils {

func displayError(viewController: UIViewController, title: String, message: String, action: UIAlertAction?) {
let ac = UIAlertController(title: title,
message: message,
preferredStyle: .alert)

if action == nil {
ac.addAction(UIAlertAction(title: "Ok", style: .cancel))
} else {
ac.addAction(action!)
}

DispatchQueue.main.async {
viewController.present(ac, animated: true)
}
}
}

提前谢谢您。

最佳答案

适用于 swift 5、iOS 13*

包括。解决:“keyWindow”在 iOS 13.0 中已弃用

我更喜欢将消息保存在一个单独的类 class GlobMessage: UIAlertController { 中,从各种 VC 中调用它们。基于 Youssef 和 How to resolve: 'keyWindow' was deprecated in iOS 13.0 的回答

class GlobMessage: UIAlertController {
static func MessageXYZ(){
///needs 'extension UIWindow'
///'static' allows to call from various VC‘s


if let keyWindow = UIWindow.key {
//found calling VC

//create text for Message
let header:String = //"⚠️ deactivated!"

let body01:String = """

your message here.
Second row of message.
"""

// assemble body
let body:String = body01 //+ body02 + body03 + body04 + body05 + body06 + body07 + body08 + body09 + body10 + body11 + body12 + body13 + body14 + body15 + body16 + body17 + body18 + body19 + body20

//buttons with functions
let OK = UIAlertAction(title: "OK", style: .default) {
UIAlertAction in
//your code here
}
let NOK = UIAlertAction(title: "❌not jet", style: .destructive) {
UIAlertAction in
//your code here
}

//assemble message
let Message = UIAlertController(title: header, message: body, preferredStyle: .alert)
Message.addAction(OK)
//Message.addAction(NOK)

//present message
keyWindow.rootViewController!.present(Message, animated: true, completion: nil)
}//end if let keyWindow
}//end static func MessageXYZ()

}//end class GlobMessage


//MARK: -
extension UIWindow {
/// source: https://stackoverflow.com/questions/57134259/how-to-resolve-keywindow-was-deprecated-in-ios-13-0
/// what’s the calling VC?:
/// Usage:
/// if let keyWindow = UIWindow.key {
/// // Do something
/// ....
/// keyWindow.rootViewController!.present(Message, animated: true, completion: nil)
/// }//end if let keyWindow
///
static var key: UIWindow? {
if #available(iOS 13, *) {
return UIApplication.shared.windows.first { $0.isKeyWindow }
} else {
return UIApplication.shared.keyWindow
}//end if else
}//end static var key
}//end extension UIWindow

关于ios - Swift:从实用程序类调用 UIAlertController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43126569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com