【问题标题】:How do I animate a view when presenting a UIViewController?呈现 UIViewController 时如何为视图设置动画?
【发布时间】:2021-03-13 07:18:29
【问题描述】:

我有一个自定义的alert,它在UIViewController 上显示为UIView。所以当我想展示alertpresent UIViewController 带来alert。我遇到的问题是我想在 alert 显示时做一个简单的动画。但由于它以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
    })
}

alertViewoutletalert UIView,在UIViewController 内。我想这是我应该制作动画的,但我该把代码放在哪里呢?出现UIViewController 时如何实现它?我也尝试过使用onView.view 对其进行动画处理。我看到的问题是,如果我将动画代码放在presenting 之前,那就太早了,如果是在呈现之后,那就太晚了。

【问题讨论】:

  • 您是否尝试过将视图的背景颜色不透明度设置为 0.5。

标签: ios swift animation uiviewcontroller


【解决方案1】:

如果你想保持这个逻辑,那么我建议你在viewDidLoad 中设置初始视图状态并在viewWillAppear 之后运行动画。 但我建议使用custom transitions

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多