自己的AlertController

Own AlertController

对于我的应用程序,我想实现自己的 AlertController。但我希望具有与 UIAlertController 相同的呈现行为:使用半透明背景使整个屏幕变暗一点,并且警报动画出现。我不希望它以模态呈现形式出现。

理想情况下,我想用 present-method 像 UIAlertView 一样展示我的 AlertView,例如:

let alert = MyAlertController(type: .example)
present(alert, animated: true, completion: nil)

编辑:对不起,在我看来很明显我想要什么但是再次阅读问题我看到了问题......所以这就是我已经尝试过的远的。我创建了 UIViewController 的子 class,您可以在下面看到(缩短的)代码。

当前行为:当我呈现此 ViewController 时,它只是以模态方式呈现,而不是使屏幕变暗并弹出我的视图。我知道我需要实现动画,但在我想到达

之前

期望的行为:我可以像使用 UIAlertController 一样使用我的 class(见上文)。我只需要初始化Controller,然后调用present。我怎样才能做到这一点?我认为这一定是有可能的,因为 UIAlertController 也使用了提到的现在方法。谢谢!

class FRAlertController: UIViewController {

private var alertView: UIView!


private var alertViewCenterXConstraint: NSLayoutConstraint!
private var alertViewCenterYConstraint: NSLayoutConstraint!


init(type: FRAlertControllerType, buttons: Bool = true) {
    super.init(nibName: nil, bundle: nil)

    setupView(type: type, buttons: buttons)
}

private func setupView(type: FRAlertControllerType, buttons: Bool) {        
    setupAlertView()
}

private func setupAlertView() {
    alertView = UIView()
    alertView.backgroundColor = .white
    view.addSubview(alertView)
    alertView.translatesAutoresizingMaskIntoConstraints = false

    alertViewCenterXConstraint = NSLayoutConstraint(item: alertView!, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0)
    alertViewCenterYConstraint = NSLayoutConstraint(item: alertView!, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0)

    let widthConstraint = NSLayoutConstraint(item: alertView!, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width
        , multiplier: 0.7, constant: 0)
    let aspectRatio = NSLayoutConstraint(item: alertView!, attribute: .width, relatedBy: .equal, toItem: alertView, attribute: .height, multiplier: 1.05, constant: 0)

    view.addConstraints([
        alertViewCenterXConstraint,
        alertViewCenterYConstraint,
        widthConstraint,
        aspectRatio
    ])
}


override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = UIColor.black.withAlphaComponent(0.4)
}
}

要使用自定义动画呈现视图控制器,请执行以下操作:

  1. 创建您要呈现的视图控制器。
  2. 创建您的自定义转换委托对象 (UIViewControllerTransitioningDelegate) 并将其分配给视图控制器的 transitioningDelegate 属性。当被问到时,您的转换委托的方法应该创建和 return 您的自定义动画对象。
  3. 将视图控制器的 modalPresentationStyle 设置为 .custom

调用present:animated:方法呈现视图控制器。

参考文献:

Apple docs
Nice example from Raywenderlich