UIButton动态调整大小

15
我正在创建一个菜单,我希望按钮在屏幕上 "弹出"。基本上,我想从 0px 的尺寸开始,然后到达按钮的完整尺寸。如果需要的话,我可以动画化 alpha 和位置,但无法调整尺寸,我认为这是因为按钮上有一张图片。
如果我使用 UIButtonTypeRoundRect,您可以看到图像后面的按钮被动画化了,但该图像是静态的。
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[UIImage imageNamed:@"settings.png"] forState:UIControlStateNormal];
button.frame = CGRectMake(20, 20, 0, 0);
button.alpha = 0;
[self.view addSubview:button];
CGRect frame = button.frame;
[UIView beginAnimations:@"button" context:nil];
[UIView setAnimationDuration:1];
button.alpha = 1;
frame.size.width += 53;
frame.size.height += 53;
button.frame = frame;
[UIView setAnimationDelegate:self];
[UIView commitAnimations];

Alpha已经生效了,但是调整大小没有生效。我也尝试使用stretchableImageWithLeftCapWidth来为其提供上下文或其他内容,但无济于事。

感谢你的帮助。


你尝试过将按钮设置为“缩放填充”吗? - iwasrobbed
是的,我记得曾经尝试过那个。谁抢了你? - Rudiger
2个回答

32

你可以尝试使用以下代码:

button.transform = CGAffineTransformMakeScale(1.5,1.5);
button.alpha = 0.0f;

[UIView beginAnimations:@"button" context:nil];
[UIView setAnimationDuration:1];
     button.transform = CGAffineTransformMakeScale(1,1);
     button.alpha = 1.0f;
[UIView commitAnimations];

你的按钮应该开始时略大一些,然后缩小回来。如果这样能正确地缩放,请根据需要调整比例因子。


谢谢,我会看一下并回复你。 - Rudiger
那一开始没起作用。Button = CGAffineTransformMakeScale(1.5,1.5); 报错了。但基本上你可以使用 button.transform = CGAffineTransformMakeScale(1.5,1.5);,它会像我需要的那样动画缩放增加。谢谢 :) - Rudiger
太棒了 - 我修改了代码示例,以便其他可能想要使用它的人可以使用。 - davbryn

6

针对Swift更新:

您可以将此代码插入到与按钮绑定的任何IBAction中,以便在触摸按钮时对其进行动画处理。

    // animate button
    // play with the scale (1.25) to adjust to your liking
    yourButton.transform = CGAffineTransformMakeScale(1.25, 1.25)
    yourButton.alpha = 0.0

    UIView.beginAnimations("yourButton", context: nil)
    // play with the animationDuration to adjust to your liking
    UIView.setAnimationDuration(0.25)
    yourButton.transform = CGAffineTransformMakeScale(1.0, 1.0)
    yourButton.alpha =  1.0

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