2013-06-01 78 views
1

我想在屏幕的最下方水平放置一個圖像(不管它是模擬器還是iPhone4,iPhone5等)。基本上我只需要將其設置爲screen_height - image_height。如何以編程方式將圖像對齊到屏幕底部?

UIImage *img = [UIImage imageNamed:@"my-image.png"]; 
    UIImageView *imgView = [[UIImageView alloc]initWithImage:img]; 
    imgView.frame = CGRectMake(0, 0, img.size.width/2, img.size.height/2); 

    CGRect screenBounds = [[UIScreen mainScreen] bounds]; 
    CGFloat screenScale = [[UIScreen mainScreen] scale]; 
    CGSize screenSize = CGSizeMake(screenBounds.size.width * screenScale, screenBounds.size.height * screenScale); 

    CGRect frame = imgView.frame; 
    frame.origin.x = 0; 
    frame.origin.y = screenSize.height - img.size.height; 
    imgView.frame = frame; 

    [self.view addSubview:imgView]; 

我在做什麼錯? 0,0是屏幕的左上角,所以我不明白爲什麼screen_height - image_height在這裏是錯誤的...?

+0

你的'self.view'覆蓋整個屏幕? 'frame'中的值與* superview *相關,而不是屏幕。 – Mar0ux

回答

1

確保在計算視圖控制器視圖的框架時正確計算-viewWillAppear中的位置指標。在-viewDidLoad框架對應於從NIB加載的度量標準,並且如果您的XIB配置爲3,5英寸顯示器,則視圖將在4英寸顯示器(iPhone 5)上更高。

2

代替使用屏幕高度的,使用上海華視圖高度:

self.view.frame.size.height 

作爲子視圖被放置在它的父幀,在屏幕的不是框架的條款。

您也有一個邏輯錯誤,因爲您將圖像視圖幀高度設置爲img.size.height/2,然後使用img.size.height來設置y座標。

+0

謝謝@Wain +1,解決了我的問題:=) – PeterK

+0

嗯..看來這個視圖認爲它註定要在iphone4上。它將圖像完美地放置在模擬器中,但在我的iphone5上,圖像比它應該高出約200px。 – patrick

+0

這是一個不同的問題,涉及到自動調整大小。如果self.view位於視圖控制器和頂層,那麼視圖控制器應該爲你做。如果不是,那麼您應該將其框架設置爲您要添加到視圖的邊界,然後再將其設置爲子視圖。並將autoresizingMask設置爲靈活的寬度和高度。 – Wain

1

將子視圖對準屏幕底部然後使用自動調整大小的掩碼來確保底部邊距保持爲0。即使超級視圖的幀發生變化,這也會使子視圖保持其超級視圖的底部對齊。

例如

UIImage *img = [UIImage imageNamed:@"my-image.png"]; 
UIImageView *imgView = [[UIImageView alloc]initWithImage:img]; 
imgView.frame = CGRectMake(0, 0, img.size.width, img.size.height); 
CGRect frame = imgView.frame; 
frame.origin.x = 0; 
frame.origin.y = self.view.frame.size.height - img.size.height; 
imgView.frame = frame; 
imgView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin; 
0

如果你真的想迫使它在屏幕的底部:

CGRect screenBounds = [UIScreen mainScreen].bounds; 
CGRect viewFrameOnScreen = [[view superview] convertRect:view.frame toView:nil]; 
viewFrameOnScreen.origin.y = screenBounds.size.height - viewFrameOnScreen.size.height; 
view.frame = [[view superview] convertRect:viewFrameOnScreen fromView:nil]; 

但我懷疑你要無條件地迫使它在屏幕的底部,即使有一個標籤欄或那裏的東西。除了在特殊情況下,意見不應超出其父視圖的界限。如果你只是想要它在父視圖的底部,那麼

view.frame.origin.y = [view superview].bounds.size.height - view.frame.size.height; 
相關問題