ios - 如何为 UINavigationBar 的后退按钮创建投影?

标签 ios swift uinavigationbar back-button dropshadow

我创建了一个半透明的导航栏并将其色调颜色设置为白色。但是,有一个包含 map 的特定 VC,有时 map 上的白色后退按钮不太明显。

因此,我创建了一个带阴影的后退按钮图像,并使用 navigationController?.navigationBar.backIndicatorImage 将其设置在该 VC 的 viewWillAppear 中,并在VC不在栈顶通过

func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        viewController.viewWillAppear(animated)
}

以前的VC。这很好用。

但是,当我测试从 map VC 跨越中途到前一个 VC 但随后释放跨越时, map VC 不会被解雇但仍会触发 viewWillAppear 之前的 VC,此时 backIndicatorImage 设置为普通图像,这是我不希望的。

我怎样才能实现目标?或者有什么方法可以为 UINavigationController 中的特定 VC 在 UINavigationBar 的后退按钮上设置投影?

最佳答案

UINavigationControllerDelegate 有一个名为 navigationController(_:willShow:animated:) 的方法,您可以使用它与导航 Controller 推送/弹出动画一起制作动画。

简而言之,您应该子类化 UINavigationController 并使其成为自身的委托(delegate):

import UIKit

class AppNavigationController: UINavigationController {
    override func viewDidLoad() {
        super.viewDidLoad()
        delegate = self
    }
}

extension AppNavigationController: UINavigationControllerDelegate {
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        guard animated, let vc = viewController as? ShadowBackButtonProtocol, vc.shouldAddShadowToImage, let image = vc.myImage else {
            return
        }

        navigationController.transitionCoordinator?.animate(alongsideTransition: { (context) in
            if vc.shouldAddShadowToImage {
                // Add your shadow
            } else {
                // Remove the shadow
            }
        }, completion: nil)
    }
}

当然,两个 View Controller 都应该实现ShadowBackButtonImage:

protocol ShadowBackImageButton {
    var shouldAddShadowToImage: Bool { get }
    var myImage: UIImage? { get }
}

extension MyViewController: ShadowBackImageButton {
    var shouldAddShadowToImage: Bool { return true }
    var myImage: UIImage? { return navigationController?.navigationBar.backIndicatorImage }
}

extension AnotherSubclassOfViewController: ShadowBackImageButton {
    var shouldAddShadowToImage: Bool { return false }
    var myImage: UIImage? { return navigationController?.navigationBar.backIndicatorImage }
}

如果你问我,我更愿意在必须添加阴影的 View Controller 上添加一个 UIView 并简单地模仿 UINavigationBar 外观,如 navigationController(_:willShow:animated) 在执行back 动画时出现了一些问题(这可能是一个错误)。

关于ios - 如何为 UINavigationBar 的后退按钮创建投影?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50142386/

相关文章:

ios - 制作一个 iOS "forward"按钮

ios - iOS swift 拖动2个元素

iOS : Firebase Send/Save Data in chunks

swift - 从 ViewController 访问 AppDelegate 中的对象

ios - 按搜索后搜索栏消失

ios - AVPlayerLooper 每次迭代后黑色闪烁

ios - 调用 "[super layoutSubviews]"抛出 "[__NSArrayM objectAtIndex:]: index 1 beyond bounds"异常

ios - 如何在 Swift 中获取相对于 UIWindow 的 UIBarButtonItem 的框架?

ios - 使用多个 UIViews 而不是多个 UIViewControllers

iphone - 显示临时 subview