2017-01-30 46 views
0

我有一個動畫,以編程方式在屏幕上向上移動三個按鈕。但是,當我在iPhone 6或iPhone 4的模擬器上測試它時,按鈕的位置都是錯誤的(但只適用於iPhone 5)。我該如何解決。這些按鈕是以編程方式構建的,所以我無法真正使用自動佈局將它們放置在視圖控制器上。如何使用按鈕動畫實現自動佈局

-(IBAction)Search:(id)sender { 

self.button.frame = CGRectMake(124, 475, 78, 72); 

self.buttonTwo.frame = CGRectMake(124, 475, 78, 76); 

self.buttonThree.frame = CGRectMake(124, 475, 78, 76); 

// animate 
[UIView animateWithDuration:0.75 animations:^{ 
    self.button.frame = CGRectMake(13, 403, 78, 72); 
    self.buttonTwo.frame = CGRectMake(124, 347, 78, 76); 
    self.buttonThree.frame = CGRectMake(232, 403, 78, 76); 
+0

爲什麼你不能使用autolayout?即使它是以編程方式創建的,你仍然可以定位它們。可以創建NSLayoutConstraints的實例。 – Joshua

回答

0

您對框架使用固定值,但屏幕寬度和/或高度不同。

如果它們是正確的iPhone 5-5s(也稱爲iPhone 4" ),然後處理它的方式是:

-(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/588) * screenHeight; 
CGFloat width = (78/320) * screenWidth; 
CGFloat height = (72/588) * 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/320) * screenWidth; 
    CGFloat lowerY = (403/588) * screenHeight; 
    self.button.frame = CGRectMake(firstX, lowerY, width, height); 

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

    CGFloat thirdX = (233/320) * ScreenWidth; 
    self.buttonThree.frame = CGRectMake(thirdX, lowerY, width, height); 
}]; 
} 

這將擴大一切行動的規模,並保持相對位置。注意:UIButtons會有相同的文字大小,你可以使用這些數字直到你得到想要的效果,希望這會有所幫助,

+0

我需要Objective-C中的這個。謝謝! – Elizabeth429

+0

這是相同的代碼,只是次要語法chang ES。完成。 –