【问题标题】:Rotate BarButtonItem by 45 degrees (animated)将 BarButtonItem 旋转 45 度(动画)
【发布时间】:2025-12-06 08:20:06
【问题描述】:

看起来动画不是我的专长:/

在我的导航栏中,我有一个自定义 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 设置动画?

提前致谢。

问候

【问题讨论】:

    标签: ios animation rotation uibarbuttonitem


    【解决方案1】:

    不知道为什么会这样(我的猜测是在进行转换时,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);
    }];
    

    【讨论】:

    • 您好,很抱歉回复晚了,我度过了一个忙碌的周末。我今晚会试试,然后告诉你。谢谢。
    • 很好,非常感谢,效果很好。仍然想知道为什么它最初不起作用,但现在它很好!