2012-10-12 21 views
1

在過去,我已經做了以下內容:放的UIView上的UIButton,仍然有它突出

thumbnailButton = [[UIButton alloc] initWithFrame: thumbnailButtonFrame]; 
[thumbnailButton addTarget:self action:@selector(thumbnailButtonPushed:) forControlEvents:UIControlEventTouchUpInside]; 
[thumbnailButton setBackgroundImage: thumbnailButtonImage forState: UIControlStateNormal]; 
[thumbnailButtonImage release]; 

這創造出了它的縮略圖像一個按鈕,當推它像是把一個灰色突出顯示在其上(非常像在照片應用程序中,當您選擇要從縮略圖列表中顯示的照片時)。

我有一個場景,現在我有一個UIView類,它在drawRect方法中繪製圖形。我想把這個UIView放在UIButton上,並且如果我添加一個圖像,它會以同樣的方式突出顯示。我想這樣做,而不需要繼承UIButton。這可能嗎?

+0

您是否不使用2張圖像,並根據是否選擇了按鈕或未選擇按鈕來設置圖像? –

回答

3

這應該工作。然而,它可能不是您正在尋找的確切方法。

它涉及轉換UIView in UIImage

+ (UIImage *) imageWithView:(UIView *)view 
{ 
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0); 
    [view.layer renderInContext:UIGraphicsGetCurrentContext()]; 

    UIImage * img = UIGraphicsGetImageFromCurrentImageContext(); 

    UIGraphicsEndImageContext(); 

    return img; 
} 

然後只需在您的代碼中調用此方法即可。

[thumbnailButton setBackgroundImage:[MyClass imageWithView:myCustomView] forState: UIControlStateNormal]; 

這可能不會給你你想要的表現,但它應該工作。

0

你可以試試這個方法。您可以有兩個圖像一個正常狀態,一個突出顯示的狀態..

btnImage = [UIImage imageNamed:@"buttonInactiveImage.png"]; 
btnImageSelected = [UIImage imageNamed:@"buttonActiveImage.png"]; 
btn = [[UIButton alloc] initWithFrame: thumbnailButtonFrame]; 
btn = [UIButton buttonWithType:UIButtonTypeCustom]; 
[btn setBackgroundImage:btnImage forState:UIControlStateNormal]; // Set the image for the normal state of the button 
[btn setBackgroundImage:btnImageSelected forState:UIControlStateSelected]; // Set the image for the selected state of the button 

這樣,你不要有把任何視圖按鈕