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

标签 ios swift uialertcontroller

我正在尝试制作如下所示的 UIAlertController:

Alert screenshot

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

最佳答案

您尝试做的是弹出窗口,对于当前版本的 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
    }

Update: to achieve, point 3... on your parent 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)
    }

}

关于ios - 如何在 swift ios 中创建自定义 UIAlertController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31997885/

相关文章:

ios - SwiftUI 列表仅使用给定数组的第一项

swift - Firebase 上传 URL 到实时数据库

ios - 当我点击按钮而不是 UIAlertcontroller 时创建 Action

ios - iOS 7 中的 ViewController 撤消 Segue

ios - 使用 Firebase 作为后端构建现有 Android 应用程序的 iOS 副本。如何最有效地进行测试

ios - 在展开可选值时发现 nil - spriteKit

ios - 按钮标签自动更改

ios - UITabBar 项目在 iOS 12.1 上跳回后退导航

ios - UIAlertController 中的 UIPickerView 仅在 iPad 中给出错误,而在 iPhone 中正确?

ios - 创建 UIAlertController 而不呈现它会产生警告