Reputation: 240
looks like animations are not my speciality :/
In my navigation bar I have a custom BarButtonItem, a plus, to add stuff to the list. I wanted to rotate the plus by 45 degrees so it becomes a X when it was pressed and works as a cancel button then.
I added a button as custom view to the BarButtonItem by doing this:
@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)
}
}
This seems to work fine. Now if the button is pressed I do the following:
UIView.animate(withDuration: 0.5, animations:{
self.addQuestionaryButton.customView!.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_4))
})
I can see the button starting to rotate but somehow it gets totally deformed. See the pictures for that:
Before:
After:
I don't understand why this happens. How do I correctly animate the BarButtonItem?
Thanks in advance.
Greetings
Upvotes: 3
Views: 1241
Reputation: 1297
Don't know why this is happening(my guess is when doing the transform, the frame of the customView will be messed up) but found a solution. Just put the button into another UIView and then set this UIView as the customView of the UIBarButtonItem.
When doing the animation, don't rotate the UIView, rotate the button.
Reminder: Don't forget to set the frame of this UIView.
Sample code in Objective C:
Init:
@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;
}
Code to trigger the rotation:
[UIView animateWithDuration:0.5 animations:^{
self.itemButton.transform = CGAffineTransformRotate(self.itemButton.transform, M_PI_4);
}];
Upvotes: 4