2012-09-03 88 views
1

我試圖創建一個自定義的UIButton,但是當我將背景設置爲清晰/透明時,它會用黑色填充框架的背景。我不是在IB創建這些,我需要以編程方式執行此操作。有什麼我失蹤?UIButton背景將不透明

UIButton* btn = [UIButton buttonWithType: UIButtonTypeCustom]; 
btn.frame = rect; 
[btn addTarget: self action:@selector(toggleMaster) forControlEvents: UIControlEventTouchUpInside]; 
btn.opaque = NO; 
btn.backgroundColor = [UIColor clearColor]; 
[btn setBackgroundImage: [UIImage imageNamed: [NSString stringWithFormat: @"%@_icon", self.currentKey]] forState: UIControlStateNormal]; 
[self addSubview: btn]; 

編輯: 我意識到我應該提到我在的UIView的drawRect方法這樣做。不好的做法?

+0

我沒有看到任何錯誤。可能你使用的圖像有黑色背景。你嘗試使用不同的圖像? – Neo

+0

我粘貼了你的代碼。它的工作很好。只要看看你是否設置了有效的bg圖像:[btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@「%@ _ icon」,self.currentKey]] forState:UIControlStateNormal];或者在那裏給一些硬編碼的圖像。 –

+0

難道這與在drawRect方法中做的事情有關嗎? – Chris

回答

0

我不認爲你需要設置backgroundColor,UIButtonTypeCustom默認情況下已經是透明的。你沒有嘗試過嗎?另外,圖像是否透明?大小與按鈕的大小相同?

+0

我已經試過了。它繼續黑色背景。 PNG已經有了透明的背景。它有一個圓形的角落,這是黑色的寶石曝光的地方 – Chris