如何在swift ios中创建自定义UIAlertController?

时间:2015-08-13 20:32:31

标签: ios swift uialertcontroller

我正在尝试制作看起来像这样的UIAlertController:

Alert screenshot

我们如何定制UIAlertController以获得与此图片相同的结果?

2 个答案:

答案 0 :(得分:6)

您要做的是弹出窗口,对于iOS的当前版本,您可以为iPad和iPhone实现相同的效果。

1.-首先在Storyboard或xib上构建您的设计。然后引用它。

2.-然后把它作为一个弹出窗口。

3.-也许你会想要实现popoverdelegates以避免在旋转设备时出现错误的位置。

例如:

  private static func presentCustomDialog(parent: UIViewController) -> Bool {
        /// Loads your custom from its xib or from Storyboard
        if let rateDialog = loadNibForRate() {
            rateDialog.modalPresentationStyle = UIModalPresentationStyle.Popover
            rateDialog.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve
            let x = parent.view.center

            let sourceRectX : CGFloat

            let maximumDim = max(UIScreen.mainScreen().bounds.height, UIScreen.mainScreen().bounds.width)
            if maximumDim == 1024 { //iPad
                sourceRectX = x.x
            }else {
                sourceRectX = 0
            }

            rateDialog.popoverPresentationController?.sourceView = parent.view
            rateDialog.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.allZeros
            rateDialog.popoverPresentationController?.sourceRect = CGRectMake(sourceRectX, x.y, 0, 0)
            rateDialog.popoverPresentationController?.popoverLayoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
            rateDialog.popoverPresentationController?.delegate = parent

            rateDialogParent = parent

            dispatch_async(dispatch_get_main_queue(), {
                parent.presentViewController(rateDialog, animated: true, completion: nil)
            })
            return true
        }
        return false
    }
  

更新:在您的父UIViewController上实现第3点....

public class MyParentViewController: UIViewController, UIPopoverPresentationControllerDelegate {
    /**
    This function guarantees that the CustomDialog is always centered at parent, it locates the Dialog view
     */
    public func popoverPresentationController(popoverPresentationController: UIPopoverPresentationController, willRepositionPopoverToRect rect: UnsafeMutablePointer<CGRect>, inView view: AutoreleasingUnsafeMutablePointer<UIView?>) {
        let x = popoverPresentationController.presentingViewController.view.center
        let newRect = CGRectMake(x.x, x.y, 0, 0)
        rect.initialize(newRect)
    }

}

答案 1 :(得分:2)

我在@Hugo发布时做了自定义弹出窗口,过了一段时间我找到了一个非常整洁和宏伟的方式完成的库,可以用来实现自定义弹出视图而不费吹灰之力:

这是Github上的库的链接:

https://github.com/m1entus/MZFormSheetPresentationController

它是用Objective c编写的,并且库中的样本中包含了一些快速的例子。

要将它包含在swift项目中,您需要使用名为Bridging-header

的东西