看起来动画不是我的专长:/
在我的导航栏中,我有一个自定义BarButtonItem(加号),可以将内容添加到列表中。我想将加号旋转45度,以使其在按下时变为X,然后用作取消按钮。
通过执行以下操作,我向BarButtonItem添加了一个按钮作为自定义视图:
@IBOutlet weak var addQuestionaryButton: UIBarButtonItem!
{
didSet {
let icon = UIImage(named: "add")
let iconSize = CGRect(origin: CGPoint.zero, size: icon!.size)
let iconButton = UIButton(frame: iconSize)
iconButton.setBackgroundImage(icon, for: .normal)
addQuestionaryButton.customView = iconButton
iconButton.addTarget(self, action: #selector(QuestionaryListViewController.addClicked(_:)), for: .touchUpInside)
}
}
这似乎很好。
现在,如果按下按钮,我将执行以下操作:
UIView.animate(withDuration: 0.5, animations:{
self.addQuestionaryButton.customView!.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_4))
})
我可以看到按钮开始旋转,但是不知何故它完全变形了。参见图片:
之前:
后:
我不明白为什么会这样。
如何正确设置BarButtonItem的动画?
提前致谢。
问候
最佳答案
不知道为什么会这样(我猜是在进行转换时,customView的框架会被弄乱),但是找到了解决方案。
只需将按钮放入另一个UIView,然后将此UIView设置为UIBarButtonItem的customView。
制作动画时,请勿旋转UIView,请旋转按钮。
提醒:不要忘记设置此UIView的框架。
objective-c 中的示例代码:
在里面:
@interface ViewController ()
@property (nonatomic, strong) UIButton* itemButton;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//button init
self.itemButton = [[UIButton alloc] init];
[self.itemButton setBackgroundImage:[UIImage imageNamed:@"imgName"] forState:UIControlStateNormal];
self.itemButton.frame = CGRectMake(0, 0, 30, 30);
//container for the button
UIView* btnContainer = [[UIView alloc] init];
btnContainer.frame = CGRectMake(0, 0, 30, 30);
[btnContainer addSubview:self.itemButton];
//set the container as customView of the UIBarButtonItem
UIBarButtonItem* applyButton = [[UIBarButtonItem alloc] initWithCustomView:btnContainer];
self.navigationItem.rightBarButtonItem = applyButton;
}
触发旋转的代码:
[UIView animateWithDuration:0.5 animations:^{
self.itemButton.transform = CGAffineTransformRotate(self.itemButton.transform, M_PI_4);
}];