从左侧滑动UIBarButtonItem

时间:2018-12-13 20:02:01

标签: ios swift animation uibarbuttonitem uinavigationitem

当转到第二页时,我试图在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)
        })
    }

2 个答案:

答案 0 :(得分:1)

您只需要将此自定义按钮放在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中。

答案 1 :(得分:1)

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 } 在完成块中。

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

Measure 2 = IF(HASONEVALUE('CPP'[KPI Group]),
               SUMX('CPP',
                    DIVIDE(1,'Corporate Planning Project'[Full Year 
                    Budget],0)*'CPP'[Actual Y.T.D]
                  ),
               ""
              )