2011-01-05 132 views
15

我是一個Objective C的新手。我如何將這個按鈕的背景設置爲一個圖像(圖像已經在XCode的資源文件夾中,「blue_button.png」)而不是clearColor?此外,我寧願我使用圖像作爲按鈕的形狀,而不是UIButtonTypeRoundedRect。爲UIButton設置一個背景圖像

btnClear = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain]; 

btnClear.frame = CGRectMake(115, 350, 90, 40); 

[btnClear setTitle:@"Clear" forState:UIControlStateNormal]; 

btnClear.backgroundColor = [UIColor clearColor]; 

[btnClear addTarget:self action:@selector(clearAction:) 

forControlEvents:UIControlEventTouchUpInside]; 

[self.view addSubview:btnClear]; 

我知道如何在Interface Builder中做到這一點,但我寧願瞭解如何在XCode中做到這一點。

+0

你可以做,在Interface Builder如果你使用筆尖 – Vjy 2011-01-05 19:42:51

+0

你應該接受一個答案,這是對所有參與者都有好處...... – whyoz 2016-07-11 10:21:16

回答

2

您可以使用[UIColor colorWithPatternImage:]設置圖像的背景顏色。要使用圖像,您應該將按鈕樣式更改爲自定義。

8

UIButton class reference-setBackgroundImage:forState:

創建UIButtonTypeCustom類型,而不是你的UIButtonTypeRoundedRect按鈕,如果你不想使用圓角風格。

6

您需要具有以下UIButtonTypeCustom類型來聲明按鈕:

btnClear = [[UIButton buttonWithType:UIButtonTypeCustom] retain]; 

那麼你應該可以使用如下:

[btnClear setImage:[UIImage imageNamed:@"blue_button.png"] forState:UIControlStateNormal]; 

有可以設定6個不同的控制狀態。

enum { 
    UIControlStateNormal    = 0, 
    UIControlStateHighlighted   = 1 << 0, 
    UIControlStateDisabled    = 1 << 1, 
    UIControlStateSelected    = 1 << 2, 
    UIControlStateApplication   = 0x00FF0000, 
    UIControlStateReserved    = 0xFF000000 
}; 

這裏有一些參考資料,可以幫助:

UIButton Class Reference

UIControl Class Reference

+0

這確實有效,但我現在不確定如何設置標題。我正在使用[btnClear setTitle:@"Clear" forState:UIControlStateNormal]; Linda 2011-01-05 21:16:06

+0

看看這個,看看是否有幫助。 http://stackoverflow.com/questions/1469474/setting-an-image-for-a-uibutton-in-code – 2011-01-05 21:45:17

+0

你可以設置和圖像或瓷磚,但有一些事情,你可以做的,以獲得標題顯示 – 2011-01-05 21:45:51

42

這工作:

UIButton *btnClear = [[UIButton alloc] init]; 
btnClear = [[UIButton buttonWithType:UIButtonTypeCustom] retain]; 
btnClear.frame = CGRectMake(115, 200, 90, 40); 
[btnClear setTitle:@"Clear" forState:UIControlStateNormal]; 
[btnClear setBackgroundImage:[UIImage imageNamed:@"blue_button.png"] forState:UIControlStateNormal]; 
[btnClear addTarget:self action:@selector(clearAction:) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:btnClear]; 
+3

請將此答案標記爲已接受... – 2013-11-10 06:30:42

1

無需設置按鈕UIButtonTypeCustom- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state方法也適用爲UIButtonTypeRoundedRect如果要設置按鈕的背景與互聯網上的圖像

1

,使用SDWebImage是一個優雅的選擇:

#import <SDWebImage/UIButton+WebCache.h> 

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)]; 
[button setBackgroundImageWithURL:imageURL forState:UIControlStateNormal];