首页 > 解决方案 > 呈现 UIViewController 时如何为视图设置动画?

问题描述

我有一个习惯alert,它UIViewUIViewController. 因此,当我想呈现alertIpresentUIViewController,就会出现alert. 我遇到的问题是我想alert在它显示的时候做一个简单的动画。但由于它以 a 的形式呈现,UIViewController而不仅仅是以UIView覆盖图的形式显示,因此我对如何实现这一点感到有些困惑。以下是相关代码:

static func standardMessageAlert(title: String, msg: String, action: ((_ text: String?) -> Void)? = nil) -> CustomAlertViewController? {
    let alert = CustomAlertViewController.create(title: title, message: msg)
        
    let okAction = CustomAlertAction(title: "OK", type: .normal, handler: action)

    alert?.addAction(okAction)
         
    return alert
}

的代码CustomAlertViewController非常大,但 create 方法如下所示:

static func create(title: String?, message: String?, addon: Addon? = nil, alertType: AlertType? = nil) -> CustomAlertViewController? {
    let storyboard = UIStoryboard(name: "Overlay", bundle: nil)
    guard let viewController = storyboard.instantiateViewController(withIdentifier: "CustomAlertViewController") as? CustomAlertViewController else {
            return nil
        }
        
    viewController.modalPresentationStyle = .overCurrentContext
    viewController.modalTransitionStyle = .crossDissolve
        
    viewController.alertType = alertType
    viewController.addon = addon
    viewController.alertTitle = title
    viewController.alertMessage = message
        
    return viewController
    }
...

alert如下所示:

func present(animated: Bool, onView: UIViewController? = UIApplication.rootViewController(), completion: (() -> Void)? = nil) {
    onView?.present(self, animated: animated, completion: nil)
}

动画将是这样的基本内容:

func animateView() {
    alertView.alpha = 0
    UIView.animate(withDuration: 1, animations: { [weak self] () -> Void in
        guard let self = self else { return }
        self.alertView.alpha = 1.0
    })
}

alertView是里面outletalert UIView那个UIViewController。我想这是我应该制作动画的,但我该把代码放在哪里呢?出现时如何实现它UIViewController?我也试过用onView.view它来制作动画。我看到的问题是,如果我将动画代码放在presenting它之前为时过早,而如果它在呈现之后则为时已晚。

标签: iosswiftanimationuiviewcontroller

解决方案


如果你想保持这个逻辑,那么我可以建议你设置初始视图状态viewDidLoad并在之后运行动画viewWillAppear。但我建议使用自定义过渡


推荐阅读