2012-09-14 173 views
4

我有一個標題在中間的UIButton。我想在按鈕的左側和右側顯示圖像(圖標)。在左側,它很容易,我只是設置手動座標。但在右側,當顯示旋轉並放大按鈕時,我需要將圖像沿「x」軸移動。UIButton在左側和右側的圖像

如何做到這一點?

+0

你爲什麼不嘗試添加兩個UIImageViews的爲您的按鈕的子視圖,並給他們幀? – RomanHouse

+0

我正在使用UIImageViews ...但熱設置框架爲正確的一個... –

回答

8

說你有一個UIButton叫Button1的,你可以做這樣的事情:

imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)]; 
imageView1.center = CGPointMake(25, button1.frame.size.height/2); 
imageView1.image = [UIImage imageNamed:@"ThumbsUp.png"]; 
[button1 addSubview:imageView1]; 
[imageView1 release]; 

imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)]; 
imageView2.center = CGPointMake(button1.frame.size.width - 25, button1.frame.size.height/2); 
imageView2.image = [UIImage imageNamed:@"ThumbsDown.png"]; 
[button1 addSubview:imageView2]; 
[imageView2 release]; 

這裏我們添加兩個圖像視圖按鈕,使用它們的中心放置它們。對於imageView1,我們將它設置爲距離按鈕左側25個像素。對於imageView2,我們從按鈕的寬度中減去25。

現在我們要設置旋轉代碼:

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation) interfaceOrientation duration:(NSTimeInterval)duration { 

    if (interfaceOrientation == UIDeviceOrientationPortrait || interfaceOrientation == UIDeviceOrientationPortraitUpsideDown) { 
     [button1 setFrame:CGRectMake(10, 100, 300, 50)]; 
    } else { 
     [button1 setFrame:CGRectMake(40, 50, 400, 50)]; 
    } 
    imageView2.center = CGPointMake(button1.frame.size.width - 25, button1.frame.size.height/2); 
} 

這裏我們改變取決於我們是否是縱向還是橫向的,最後我們設置imageView2中心調整爲不同的幀按鈕的框架。我們不必費心使用imageView1,因爲它保持不變。

+0

你通過添加不相關的鏈接和簽名到最後,否則很好的答案。請住手。 – jrturton

+0

當文字太大而不能在雙方留下必要的空間時會發生什麼? – thesummersign

+0

首先使用Stephen Poletto的答案[這裏]計算按鈕標題的寬度(http://stackoverflow.com/questions/3429671/how-to-get-the-width-of-an-nsstring)。然後,添加兩個UIImages的size.widths以及任何您需要的其他填充。 –