2011-05-04 49 views
2

我想創建一個自定義圖像(背景圖像)的按鈕,我已經做到了這一點。 如何分配imageview到may按鈕?ImageView和UIButton

謝謝您的回答

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
[button addTarget:self 
      action:@selector(goToGeoloc) 
forControlEvents:UIControlEventTouchDown]; 
[button setTitle:@"Show View" forState:UIControlStateNormal]; 
button.frame = CGRectMake(245.0, 8.0, 45.0, 45.0); 
UIImage *image = [UIImage imageNamed:@"ico_plan.png"]; 
UIImageView *imageView = [[UIImageView alloc]initWithImage:image]; 

回答

5

@izan你不需要單獨UIImageView顯示在UIButton

A UIButton裏面有2個UIImageView。你可以設置這兩個imageViews的圖像。

您可以使用setImage:forState:方法設置第一個圖像視圖的圖像。通過這樣做,您無法顯示該按鈕的任何標題。如果你想顯示標題以及按鈕上的圖像,你應該使用setBackgroundImage:forState:方法。

5

使用setImage方法;

- (void)setImage:(UIImage *)image forState:(UIControlState)state 

所以,你的代碼將是;

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
[button addTarget:self action:@selector(goToGeoloc) forControlEvents:UIControlEventTouchDown]; 
[button setTitle:@"Show View" forState:UIControlStateNormal]; 
button.frame = CGRectMake(245.0, 8.0, 45.0, 45.0); 

UIImage *image = [UIImage imageNamed:@"ico_plan.png"]; 
[button setImage:image forState:UIControlStateNormal]; 

或者我還想讓你的文本顯示使用;

- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state 

這將導致;

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
[button addTarget:self action:@selector(goToGeoloc) forControlEvents:UIControlEventTouchDown]; 
[button setTitle:@"Show View" forState:UIControlStateNormal]; 
button.frame = CGRectMake(245.0, 8.0, 45.0, 45.0); 

UIImage *image = [UIImage imageNamed:@"ico_plan.png"]; 
[button setBackgroundImage:image forState:UIControlStateNormal]; 

UIButton documentation; http://bit.ly/kruq5y

7

你想要的是:

[button setBackgroundImage:image forState:UIControlStateNormal]; 

[button setImage:image forState:UIControlStateNormal]; 
+0

Whta是setBackground和setImage之間的區別? – izan 2011-05-04 08:29:25

+2

這是2015年...谷歌和StackOverflow正在取代文件。 – quemeful 2015-02-12 14:32:28

0
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
[button addTarget:self 
      action:@selector(goToGeoloc) 
forControlEvents:UIControlEventTouchDown]; 
[button setTitle:@"Show View" forState:UIControlStateNormal]; 
[button setImage:[UIImage imageNamed:@"ico_plan.png"] forState:UIControlStateNormal]; 
button.frame = CGRectMake(245.0, 8.0, 45.0, 45.0); 

希望這有助於