在iOS开发中,我们可以使用翻转过渡来改变leftBarButtonItem。以下是一个简单的示例,展示了如何使用翻转过渡来改变leftBarButtonItem:
let firstBarButtonItem = UIBarButtonItem(title: "First", style: .plain, target: self, action: #selector(changeBarButtonItem))
let secondBarButtonItem = UIBarButtonItem(title: "Second", style: .plain, target: self, action: #selector(changeBarButtonItem))
@objc func changeBarButtonItem() {
let currentBarButtonItem = navigationItem.leftBarButtonItem
navigationItem.leftBarButtonItem = (currentBarButtonItem == firstBarButtonItem) ? secondBarButtonItem : firstBarButtonItem
}
navigationItem.leftBarButtonItem = firstBarButtonItem
class ViewController: UIViewController, UINavigationControllerDelegate {
// ...
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.delegate = self
}
// ...
}
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return FlipTransition()
}
class FlipTransition: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
guard let fromView = transitionContext.view(forKey: .from), let toView = transitionContext.view(forKey: .to) else { return }
containerView.addSubview(toView)
toView.alpha = 0
let duration = transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, animations: {
fromView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi/2)
toView.alpha = 1
}) { _ in
fromView.transform = .identity
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
现在,当您点击leftBarButtonItem时,它将使用翻转过渡来改变leftBarButtonItem。
领取专属 10元无门槛券
手把手带您无忧上云