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

MBH*_*MBH 2 ios swift uialertcontroller

我正在尝试使UIAlertController看起来像这样:

提醒截图

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

Hug*_*nso 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
    }
Run Code Online (Sandbox Code Playgroud)

更新:实现,点3 ...你的父母UIViewController.

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)
    }

}
Run Code Online (Sandbox Code Playgroud)