如何使用 Swift 在 iOS 应用上创建自定义对话框?

iosiphone/ipadmobile developmentswift更新于 2026/2/19 19:07:17

要在 Swift 中创建对话框,我们将使用 UIAlertController,它是 UIKit 的重要组成部分。我们将借助一个 iOS 应用程序和一个示例项目来完成此操作。

首先,我们将创建一个空项目,然后在其默认视图控制器中执行以下操作。

我们将创建一个 UIAlertController 对象。

let alert = UIAlertController.init(title: title, message: description, preferredStyle: .alert)

我们将创建一个操作

let okAction = UIAlertAction.init(title: "Ok", style: .default) { _ in
   print("您点击了 ok")
   //此处为自定义操作。
}

我们将操作添加到警报并呈现它

alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)

现在我们将其转换为函数 −

func createAlert(withTitle title:String,andDescription description: String) {
   let alert = UIAlertController.init(title: title, message: description, preferredStyle: .alert)
   let okAction = UIAlertAction.init(title: "Ok", style: .default) {
       _ in print("您点击了"ok")
      //此处为自定义操作。
   }
   alert.addAction(okAction)
   self.present(alert, animated: true, completion: nil)
}

现在我们将在 viewWillLayoutSubviews 方法中调用该函数,在设备上运行该函数时,效果如下。

override func viewWillLayoutSubviews() {
   self.createAlert(withTitle: "This is an alert", andDescription: "Enter your description here.")
}

这将产生如下所示的结果。



相关文章



关于我们 | 隐私条款 | 学习路线
返回顶部