首页 > 解决方案 > 推动视图控制器时快速背景颜色

问题描述

我有两个白色视图控制器。当我尝试推动第二个视图控制器时,我注意到一个灰色背景(基本上它在过渡期间会改变 alpha 值)。是否有任何技巧可以禁用此淡入淡出?我只希望我的背景是白色的在此处输入图像描述

标签: swiftuiviewcontrollertransition

解决方案


Using a UIViewControllerAnimatedTransitioning would definitely be the "correct" way, but it seems you really want to not use it.

If you want to "hack" it, then swizzling is the way to go.

Here is an extension on UIView that prevents the underlying class _UIParallaxDimmingView from being displayed.

extension UIView {
    static func preventDimmingView() {
        guard let originalMethod = class_getInstanceMethod(UIView.self, #selector(addSubview(_:))), let swizzledMethod = class_getInstanceMethod(UIView.self, #selector(swizzled_addSubview(_:))) else { return }
        method_exchangeImplementations(originalMethod, swizzledMethod)
    }

    static func allowDimmingView() {
        guard let originalMethod = class_getInstanceMethod(UIView.self, #selector(addSubview(_:))), let swizzledMethod = class_getInstanceMethod(UIView.self, #selector(swizzled_addSubview(_:))) else { return }
        method_exchangeImplementations(swizzledMethod, originalMethod)
    }

    @objc func swizzled_addSubview(_ view: UIView) {
        let className = "_UIParallaxDimmingView"
        guard let offendingClass = NSClassFromString(className) else { return swizzled_addSubview(view) }
        if (view.isMember(of: offendingClass)) {
            return
        }
        swizzled_addSubview(view)
    }
}

I would recommend using it along the lines of this:

class SomeViewController: UIViewController {

    func transition(to viewController: UIViewController) {
        navigationController?.delegate = self
        navigationController?.pushViewController(viewController, animated: true)
    }
}


extension SomeViewController: UINavigationControllerDelegate {
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        UIView.preventDimmingView()
    }

    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        UIView.allowDimmingView()
    }
}

Of course if you want this to make it through App Store review, you will likely get flagged for the "_UIParallaxDimmingView" string. I would recommend initializing it from a byte array instead:

let className = String(bytes: [95, 85, 73, 80, 97, 114, 97, 108, 108, 97, 120, 68, 105, 109, 109, 105, 110, 103, 86, 105, 101, 119], encoding: .utf8)!

gif


推荐阅读