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

时间:2019-07-17 19:03:06

标签: swift uikit uinavigationbar

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

当然可以手动创建UILabel并相应地设置navigationBar.titleView。 但是,这对于希望解决的简单问题似乎花费了太多精力。另外,它不适用于UInavigationBar上的大标题。

1 个答案:

答案 0 :(得分:-1)

标题文本可通过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
}
相关问题