如何以编程方式调整按钮动画的大小

时间:2017-02-04 23:39:18

标签: ios objective-c autolayout translate-animation

我是Objective-C的新手。我创建了一个向上移动3个按钮的动画。这些按钮包含图像。但是,当此按钮动画发生时,它会调整按钮图像的大小并使其变大。我试图纠正下面的代码来调整按钮图像的大小,但我仍然得到巨大的按钮。有人可以帮帮我吗?它应该是宽度:78高度:76。我尝试更换宽度和高度,但它仍然无法正常工作。注意:只需更正代码,我不需要完全不同的答案。

-(IBAction)Search:(id)sender {

CGFloat screenWidth = self.view.bounds.size.width;
CGFloat screenHeight = self.view.bounds.size.height;

CGFloat normalizedX = (124 / 320); // You calculate these 'normalized' numbers, possibly from a designer's spec.
// it's the percent the amount should be over, as number from 0-1.
// This number is based on screen width of 320 having x 124 pt.

CGFloat startingX = normalizedX * screenWidth;
CGFloat startingY = (475 / 200) * screenHeight;
CGFloat width = (42 / 40) * screenWidth;
CGFloat height = (30 / 30) * screenHeight;

CGRect startingRect = CGRectMake(startingX, startingY, width, height);

self.button.frame = startingRect;
self.buttonTwo.frame = startingRect;
self.buttonThree.frame = startingRect;

// animate
[UIView animateWithDuration:0.75 animations:^{
    CGFloat firstX = (13 / 770) * screenWidth;
    CGFloat lowerY = (403 / 370) * screenHeight;
    self.button.frame = CGRectMake(firstX, lowerY, width, height);

    CGFloat secondX = (124 / 424) * screenWidth;
    CGFloat upperY = (347 / 447) * screenHeight;
    self.buttonTwo.frame = CGRectMake(secondX, upperY, width, height);

    CGFloat thirdX = (232 / 680) * screenWidth;
    self.buttonThree.frame = CGRectMake(thirdX, lowerY, width, height);
}];
 }

1 个答案:

答案 0 :(得分:2)

在我看来,你的高度和宽度数学是错误的。

(42/40)* screenWidth将简化为(1)* screenWidth,或屏幕的整个宽度(表达式42/40将使用整数数学运算,结果为1.0。如果使用浮点数,你会得到1.05 * screenWidth,这会使图像更大。)

您的身高计算存在类似问题。您将按钮设置为屏幕的整个高度,稍微宽一些。