我试图让我的UIBarButtonItem
从右侧滑入leftBarButtonItem
位置。
滑动到错误的位置,然后在设置为leftBarButtonItem
或根本不可见时跳转。这就是我现在正在尝试的事情..
func createLeftBarButton() {
// Get the nav bar we'll be working with
var toolbar = self.navigationItem
// Initialise our button
cancelButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
cancelButton.setTitle("+", forState: UIControlState.Normal)
cancelButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
cancelButton.addTarget(self, action: "cancel:", forControlEvents: .TouchUpInside)
cancelButton.titleLabel?.font = UIFont(name: "Courier", size: 34.0)
// Create a placeholder to get the position and size of the leftBarButtonItem
placeholderView = UIView(frame: cancelButton.bounds)
placeholderView.backgroundColor = UIColor.clearColor()
toolbar.leftBarButtonItem = UIBarButtonItem(customView: placeholderView)
// Get the frame and position of the placeholderView
var finalFrame: CGRect = self.view.convertRect(placeholderView.bounds, fromCoordinateSpace: placeholderView)
// Set the frame for the button to the right of the final location.. this is probably wrong at the moment.
cancelButton.frame = CGRectMake(-1 * cancelButton.bounds.size.width, finalFrame.origin.y, cancelButton.bounds.size.width, cancelButton.bounds.size.height)
// Add the button to the view
self.navigationController?.navigationBar.addSubview(cancelButton)
// Animate it to the final position
UIView.animateWithDuration(0.2, animations: {
self.cancelButton.frame = finalFrame
}, completion: { _ in
// Finally set it to the leftBarButtonitem
toolbar.leftBarButtonItem = UIBarButtonItem(customView: self.cancelButton)
})
}
答案 0 :(得分:1)
使用占位符视图/子视图的方法有点过于复杂。因此,您的代码根本不显示任何内容,因为您的cancelButton没有框架,然后您的占位符视图继承该空框架。但即便如此,你仍然会遇到问题,按钮会在下方滑动,然后再回弹。
认为这可以实现您的目标:
func createLeftBarButton() {
// Get the nav bar we'll be working with
var toolbar = self.navigationItem
// Initialise our button
cancelButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
cancelButton.setTitle("+", forState: UIControlState.Normal)
cancelButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
cancelButton.addTarget(self, action: "cancel:", forControlEvents: .TouchUpInside)
cancelButton.titleLabel?.font = UIFont(name: "Courier", size: 34.0)
cancelButton.frame = CGRectMake(0, 0, 20, 20)
// Create a placeholder to get the position and size of the leftBarButtonItem
toolbar.leftBarButtonItem = UIBarButtonItem(customView: cancelButton)
var delta = self.cancelButton.frame.size.width
cancelButton.frame = CGRectOffset(cancelButton.frame, -delta, 0.0)
// Animate it to the final position
UIView.animateWithDuration(0.2, animations: {
self.cancelButton.frame = CGRectOffset(self.cancelButton.frame, delta, 0.0)
}, completion: { _ in
})
}