1

所以,我有一个 UIButton(由一个图像组成),当我点击它时应用一个 CGAffineTransform 以突出它所处的状态:

- (void)animateMasterAddButton
{
    CGAffineTransform buttonTransform;

    // Button state hasn't been changed at this point, so selected == NO applies to when the button is *about* to be selected 
    if(self.masterAddButton.selected == NO)
    {
        CGAffineTransform buttonRotationTransform = CGAffineTransformMakeRotation((135.0 * M_PI) / 180);
        buttonTransform = CGAffineTransformConcat(CGAffineTransformIdentity, buttonRotationTransform);
    }
    else
    {
        buttonTransform = CGAffineTransformIdentity;
    }

    [UIView animateWithDuration: 0.3
                     animations: ^{
                         self.masterAddButton.transform = buttonTransform;
                     }];
}

如果我将设备保持在相同的方向,这可以正常工作。但是,一旦我转动设备,UIButton 就会消失,但前提是选择了 UIButton(即,仅当旋转变换生效时)。我在视图控制器的willRotateToInterfaceOrientation:duration:方法中记录了按钮的框架和边界,结果如下:

在未选择按钮的情况下旋转设备:

框架:{{8, 8}, {57, 57}}
边界:{{0, 0}, {57, 57}}(这些是正确的值)

选择按钮旋转设备:

帧:{{-4, -4}, {80, 80}}
边界:{{0, 0}, {0, 113.137}}

在第二组结果中,框架是正确的,因为旋转后的图像有它的角,所以会占用更多的空间。然而,界限表明有些事情是古怪的。我猜由于边界宽度为零,按钮在那里但太窄而无法渲染。

谁能告诉我为什么会发生这种情况,以及我该如何解决?

4

1 回答 1

0

搞定了,有点侧身思考。基本上,一旦旋转动画完成,转换后的按钮图像就会被替换为与动画应用旋转量相同的版本(我编写了一个 UIImage 类别方法来执行此过程)。然后使用 禁用按钮上的转换CGAffineTransformIdentity。由于旋转设备时按钮上不存在任何变换,因此它保持不变:-)

这是代码:

- (void)animateMasterAddButton
{
    CGFloat addButtonRotationAngle = AddButtonRotationAngle * -1.0;    // AddButtonRotationAngle is a const float defined at the top of .m file
    CGAffineTransform buttonTransform;
    UIImage *rotatedAddButtonImage = [UIImage imageNamed: @"Add button"];

    if(self.masterAddButton.selected == NO)
    {
        addButtonRotationAngle =  AddButtonRotationAngle;
        rotatedAddButtonImage = [UIImage rotatedImageFromImage: rotatedAddButtonImage withAngle: (addButtonRotationAngle * M_PI) / 180];
        // rotatedImageFromImage:withAngle: is a self-written category method on UIImage
    }

    CGAffineTransform buttonRotationTransform = CGAffineTransformMakeRotation((addButtonRotationAngle * M_PI) / 180);
    buttonTransform = CGAffineTransformConcat(CGAffineTransformIdentity, buttonRotationTransform);

    [UIView animateWithDuration: 0.3
                     animations: ^{
                         self.masterAddButton.transform = buttonTransform;
                     }
                     completion: ^(BOOL finished) {
                         [self.masterAddButton setImage: rotatedAddButtonImage forState: UIControlStateNormal];
                         self.masterAddButton.transform = CGAffineTransformIdentity;
                     }];
}
于 2012-09-11T10:13:27.333 回答