在iPhone上的popover中呈现UIAlertController ActionSheet

Ash*_*lls 14 iphone popover ios uialertcontroller

我正在创建和呈现ActionSheet如下:

let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
alertController.modalPresentationStyle = .Popover

// Add some buttons

alertController.popoverPresentationController?.delegate = self
alertController.popoverPresentationController?.barButtonItem = someBarButton

self.presentViewController(alertController, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

这工作正常在iPad上,不过alertController.popoverPresentationControllernil在iPhone上.

我已经成功地使用自适应segue样式在iPhone上使用自适应segue样式呈现弹出窗口并实现adaptivePresentationStyleForPresentationController委托方法以返回正确的UIModalPresentationStyle但是我已经卡住了如何在代码中执行它,UIAlertController因为它popoverPresentationController在iPhone 上没有

Kor*_*ton 7

UIAlertController并不意味着是一个popover.评论中似乎存在一些争议.如果它实际上尊重.Popover风格,那么上面的代码将无效.为什么?因为它需要在popoverPresentationController对象上有一个sourceView和一个sourceRectset来知道指向箭头的位置.如果您将UIAlertController交换为UIViewController,它将崩溃,因为这些值未设置.具有讽刺意味的是,如果您尝试强制打开popoverPresentationController,它将崩溃:

alertController.modalPresentationStyle = .Popover
alertController.popoverPresentationController!.sourceView = sender // CRASH!!!
alertController.popoverPresentationController!.sourceRect = sender.bounds
Run Code Online (Sandbox Code Playgroud)

有关如何实现iPhone popover(除了UIAlertController之外的其他所有内容)的所有详细信息,请查看我的iPhone Popover博客文章.

popover表示控制器为零的事实很明显,它不应该是一个popover.

表视图替代

您可以将UITableViewController视为此处的替代品.使用Grouped样式实际上在popovers中看起来相当不错.

选择器

您可能会一遍又一遍地遇到此问题,您希望用户只从几个选项中进行选择.我建议你将你要使用的任何用户界面控件封装到你自己的选择器对象中.是否可以从调用代码伪装其表视图或按钮排列的实现细节,并且当在特定索引处进行选择时,您可以具有委托或闭包回调.这大概是API的样子:

class Picker: UIViewController {
    init(items: [String])
    selectionCompletion: (index: Int, item: String)->Void
}

// Usage:
let picker = Picker(["Answer A","Answer B"])
picker.selectionCompletion = { index, item in
    // handle selection
}
Run Code Online (Sandbox Code Playgroud)

这样您就可以在任何地方重复使用它,并且API非常简单