如何为导航栏标题的变化设置动画

How can I animate the change of the navigation bar title

我正在寻找在 UINavigationBar 标题上 运行 自定义 CAAnimation 的方法。 更准确地说,我正在寻找一种方法来访问显示 navigationItem.title 和 运行 动画的标签。

当然可以手动创建 UILabel 并相应地设置 navigationBar.titleView。 然而,对于一个希望很简单的问题来说,这似乎是太多的努力。另外,它不适用于 UInavigationBar 上的大标题。

标题文本可访问为 topItem.text。无法直接访问显示此文本的标签。 所以如果你想动画这个标签,你首先要在 NavigationBar 的子视图中搜索它。 然后,您可以在此标签上应用动画。 请参阅下面的示例,了解从右侧淡入新标题的示例。

/// Fades in the new title from the right
///
/// - Parameter newTitle: New title to display on the navigation item
func animateTitle(newTitle: String) {
    // Title animation code
    let titleAnimation = CATransition()
    titleAnimation.duration = 0.25
    titleAnimation.type = CATransitionType.push
    titleAnimation.subtype = CATransitionSubtype.fromRight
    titleAnimation.timingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.easeInEaseOut)

    // Find the Label which contains the topitem title
    if let subviews = navigationController?.navigationBar.subviews {
        for navigationItem in subviews {
            for itemSubView in navigationItem.subviews {
                if let largeLabel = itemSubView as? UILabel {
                    largeLabel.layer.add(titleAnimation, forKey: "changeTitle")
                }
            }
        }
    }

    navigationItem.title = newTitle
}