2014-04-30 32 views
0

我嘗試爲UIButton設置圖像。但如何設置UIButton的默認圖像?如何在Objective-C的Viewdidload中將默認圖像設置爲UIButton?

頭文件中的UIButton代碼如下所示。

@property (strong, nonatomic) IBOutlet UIButton *modeChangeButton; 

而我嘗試設置圖像大小和UIButton的默認圖像,但它不顯示圖像。代碼如下所示。

- (void)viewDidLoad 
{ 
    self.modeChangeButton = [[UIButton alloc] initWithFrame:CGRectMake(200, 450, 60, 60)]; 
    [self.modeChangeButton setBackgroundImage:[UIImage imageNamed:@"recordmode.png"] forState:UIControlStateNormal]; 
} 

如何設置UIButton的默認圖像? 在此先感謝。

+0

當你用IBOutlet聲明按鈕時,它應該從storyboard或xib中加載,爲什麼你要創建另一個uibutton實例?如果你沒有加載storyboard或xib中的按鈕,爲什麼你不在'self.view'上添加按鈕。 – KudoCC

+0

您是否重複了自己的問題? http://stackoverflow.com/questions/23378603/why-the-sender-not-called-when-i-click-the-image-of-the-button-in-objective-c/23378773#23378773 – CrimsonChris

+0

參見在其他問題上給出的答案! – uiroshan

回答

1

如果您使用的是IBOutlet,則無需重新分配按鈕。此外

- (void)viewDidLoad 
{ 
    self.modeChangeButton = [[UIButton alloc] initWithFrame:CGRectMake(200, 450, 60, 60)]; 
    [self.modeChangeButton setBackgroundImage:[UIImage imageNamed:@"recordmode.png"] forState:UIControlStateNormal]; 

    [self.view addSubView:self.modeChangeButton]; 
} 

,請檢查您的按鈕你Y位置:請嘗試如下

使用IBOutlet中:

- (void)viewDidLoad 
{ 
    self.modeChangeButton.frame = CGRectMake(200, 450, 60, 60); 

    [self.modeChangeButton setBackgroundImage:[UIImage imageNamed:@"recordmode.png"] forState:UIControlStateNormal]; 
} 

使用編程方式。不管它是不是視圖框架。

+0

我正在使用IBOutlet,它的工作。謝謝 !! – Wun

+0

不客氣:) – Natarajan

+0

不好意思...但是'self.modeChangeButton.frame = CGRectMake(200,450,60,60);'似乎沒有用... – Wun

-1
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    self.modeChangeButton = [[UIButton alloc] initWithFrame:CGRectMake(200, 450, 60, 60)]; 
    [self.modeChangeButton setBackgroundImage:[UIImage imageNamed:@"recordmode.png"] 
            forState:UIControlStateNormal]; 
} 

您錯過了超級電話viewDidLoad。我猜這可能是問題。

+0

我已經打電話給viewDidLoad了,只是沒有過去。 – Wun

+1

@Wun如果你沒有發佈所有相關的代碼,你可以期望得到更多的答案。 – CrimsonChris

0

你忘了添加你的按鈕作爲子視圖。

[self.view addSubview:self.modeChangeButton]; 
+0

我在xib中創建了一個按鈕。如果我使用addSubview,它會添加新的按鈕。 – Wun

+0

'[[UIButton alloc] initWithFrame:CGRectMake(200,450,60,60)]'給你一個全新的按鈕。如果您不打算將其添加爲子視圖,則不要創建新的。 – CrimsonChris