针对 iOS 13 Xcode 11+ Swift 5.X
UIAlertController
现在可以提供警告和操作表
警告
let alert = UIAlertController(title: "Title",
message: "Message ?",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Just Do It!", style: .destructive, handler: nil))
alert.addAction(UIAlertAction(title: "Maybe", style: .default, handler: nil))
self.present(alert, animated: true)
请注意,当点击操作按钮时,关闭警告视图是所有操作按钮的基本特性。其中
style
参数仅用于决定文本的颜色(以及一些默认顺序,按钮的顺序可以更改)。
示例处理程序函数可能如下:
func handler(_ action: UIAlertAction) {
if action.title == 'Title' {
}
}
作为一个旁注,我认为你可以只创建一个处理程序,并按照上述方式追溯触发它的元素。
我们也可以检查alert.style
,但这样我们就可以有多个默认样式的操作,我不建议这样做。
操作表
解释类似,因为主要区别在于警报会打断用户,而操作表会从底部滑动到 iPhone 上,在 iPad 上则呈现为弹出视图。
操作表的目的是根据用户当前状态指导用户决定其操作。所以你必须像处理十字路口一样对待操作表!通常没有消息,标题呈现为字幕大小的文本。
let action = UIAlertController(title: "What do you want to do with the message",
message: nil,
preferredStyle: .actionSheet)
action.addAction(UIAlertAction(title: "Cancel", style: .cancel))
for act in ["Save", "Post", "Discard"] {
action.addAction(UIAlertAction(title: act, style: .default, handler: nil))
}
self.present(action, animated: true)
上面的代码在iPhone上可以工作,但是在iPad上会在运行时崩溃,因为UIPopoverPresentationController将负责警告,并且此时它不会引用任何内容。因此,为了避免这种情况,您必须提供以下必要的代码块。
if let pop = action.popoverPresentationController {
let v = sender as! UIView
pop.sourceView = v
pop.sourceRect = v.bounds
}
同样,对于iPad而言,在弹出窗口之外的任何地方轻触都会使其消失,并调用“取消”操作按钮的完成处理程序。
希望这有所帮助 :) 话虽如此,如果您有任何疑问,请在下方评论。
self
所属的类采用了协议UIAlertViewDelegate
(在Swift中,推荐的方法是使用扩展)。 - Nicolas Miari