简单而优雅的方式来处理UIAlertController。

迅捷警报

SwiftAlert是处理UIAlertController的简单而优雅的方式。

特征

  • 使用 async/await 处理操作
  • 方法链
  • 支持 UITextField
  • 支持基于文本的操作启用或禁用
  • 支持弹出框

要求

  • 斯威夫特 5.7+
  • iOS 13.0+
  • 电视操作系统 13.0+

用法

基本警报

基本方法是使用方法链构建警报。

let alert = Alert(style: .alert)
  .title("Title")
  .message("Message")
  .action(.default("Done"))

_ = await alert.present(from: vc)

处理操作

警报关闭时,结果为 或 。 包含从操作传入的项。如果未传递任何项目,则类型为 。.done.cancel.doneVoid

let alert = Alert(style: .alert)
  .title("Delete")
  .message("Are you sure?")
  .action(.cancel("Cancel"))
  .action(.destructive("Delete")) // destructive style

switch await alert.present(from: vc) {
case .done:
  print("Delete")
case .cancel:
  print("Cancel")
}

Action Sheet (Multiple Actions)

This is an action sheet that passes multiple string items. has a selected item..done

When providing an action sheet on the iPad, you can set a popover presentation controller with method.popoverPresentation

let sheet = Alert(style: .actionSheet)
  .title("Select")
  .message("Select a fruit")
  .action(.cancel("Cancel"))
  .action(.default("Apple", item: "🍎"))
  .action(.default("Grapes", item: "🍇"))
  .action(.default("Peach", item: "🍑"))
  .popoverPresentation { popover in // for ipad
    popover.sourceView = sourceView
    popover.sourceRect = sourceRect
  }

switch await sheet.present(from: vc) {
case .done(let item):
  print("Select \(item)") // item is [🍎, 🍇, 🍑]
case .cancel:
  print("Cancel")
}

Alert with a text field

You can add and configure text fields using the method.addTextField

When a text field is added, has an item and texts..done

let alert = Alert(style: .alert)
  .title("Name")
  .addTextField {
    // Configure text field
    $0.placeholder = "Enter a name"
  }
  .action(.cancel("Cancel"))
  .action(.default("Done"))

switch await alert.present(from: vc) {
case .done(_, let texts):
  print("Name is \(texts[0])")
case .cancel:
  print("Cancel")
}

Alert with multiple text fields

You can use method for the buttons enable or disable dependng on text input.textChanged

let alert = Alert(style: .alert)
  .title("Login")
  .message("Login to service")
  .addTextField {
    $0.placeholder = "Account"
  }
  .addTextField {
    $0.placeholder = "Password"
    $0.isSecureTextEntry = true
  }
  .textChanged { texts, actions in
    let account = texts[0]
    let password = texts[1]
    for action in actions where action.style != .cancel {
      action.isEnabled = !id.isEmpty && !password.isEmpty
    }
  }
  .action(.cancel("Cancel"))
  .action(.default("Connect"))

switch await alert.present(from: vc) {
case .done(_, let texts):
  print("account: \(texts[0]), password: \(texts[1])")
case .cancel:
  print("Cancel")
}

License

MIT license. See LICENSE for details.

GitHub

点击跳转