旋转BarButtonItem 45度(带动画)

3

看起来动画不是我的强项 :/

在我的导航栏中,我有一个自定义的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动画?
提前感谢。
问候
1个回答

4

不知道为什么会出现这种情况(我猜测是在进行转换时,自定义视图的框架会被搞乱),但找到了解决方法。

只需将按钮放入另一个 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);}];

抱歉回复晚了,我周末很忙。 今晚我会尝试并告诉你结果。谢谢。 - Hardcore_Graverobber
非常好,非常感谢,那个完美地解决了问题。虽然还在想为什么一开始它没能正常工作,但现在已经好了! - Hardcore_Graverobber

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接