从左侧滑动 UIBarButtonItem

Slide UIBarButtonItem from the left

在转到二级页面时,我试图在 0.33 秒的时间内从左侧滑入后退按钮。现在动画似乎并没有这样做,即使在将持续时间减慢到 2 秒以进行视觉澄清之后也是如此。想知道是否有人可以告诉我我的代码中做错了什么以及如何改正它?

要出来说我可能只是误解了动画的某些方面是如何工作的。

func addBackButton() {
        let backButton = UIButton(type: .custom)
        backButton.setImage(#imageLiteral(resourceName: "backArrow"), for: .normal)
        backButton.setTitle("", for: .normal)
        backButton.setTitleColor(backButton.tintColor, for: .normal)
        backButton.addTarget(self, action: #selector(backAction), for: .touchUpInside)
        let backBarButtonItem = UIBarButtonItem(customView: backButton)
        backBarButtonItem.customView?.transform = CGAffineTransform(translationX: -backButton.frame.width, y: 0)
        navigationItem.leftBarButtonItems?.insert(backBarButtonItem, at: 0)
        UIView.animate(withDuration: 2, delay: 0.5, animations: {
            backBarButtonItem.customView?.transform = CGAffineTransform(translationX: 2 * backButton.frame.width, y: 0)
        })
    }

您只需将此自定义按钮放在 containerView 中,并将 containerView 设置为 UIBarButtonItem's 自定义视图。您的设置将如下所示,

let containerFrame = CGRect(origin: .zero, size: CGSize(width: 44.0, height: 44.0))
let container = UIView(frame: containerFrame)

let buttonFrame = CGRect(origin: CGPoint(x: -100, y: 0), size: CGSize(width: 44, height: 44))  
let backButton = UIButton(frame: buttonFrame)
backButton.setImage(#imageLiteral(resourceName: "backArrow"), for: .normal)
backButton.setTitle("", for: .normal)
backButton.setTitleColor(backButton.tintColor, for: .normal)
backButton.addTarget(self, action: #selector(backAction), for: .touchUpInside)
container.addSubview(backButton)

let backBarButtonItem = UIBarButtonItem(customView: container)
UIView.animate(withDuration: 2, delay: 0.5, animations: {
    backButton.transform = CGAffineTransform(translationX: 2 * backButton.frame.width, y: 0)
})

您可以检查为什么需要将自定义 button 包装在另一个 UIView here.

UIBarButtonItem 不是 UIView 子类是有原因的。如果这是您想要的效果(平台一致性表明您应该使用 UINavigationItem.setLeftBarButtonItems(_:animated:)),那么您应该将 backButton 添加到您的视图层次结构中,为其设置动画,然后将其设置为 leftBarButtonItem在完成块中。

请记住,您可能必须将它添加到导航栏视图层次结构中,以便它显示在它的顶部。这种方法还意味着您基本上是在复制导航栏的布局代码,您必须弄清楚它应该在哪里结束。

navigationController?.navigationBar.addSubview(backButton)

// layout back button in it's final spot here, either via constraints or frame math

backButton.transform = CGAffineTransform(translationX: -(button.bounds.width + leadingSpacing), translationY: 0.0)

UIView.animate(duration: 0.3, animations: {
    backButton.transform = .identity
} { completed in
    self.navigationItem.leftBarButtonItem = UIBarButtonItem
}