2011-10-26 42 views
1

我試圖創建一個具有以下特徵的的UIButton: *自定義圖像作爲其內容 *圓角 *陰影展會亮點與子視圖

使用下面的代碼將將按鈕格式化爲正確顯示並且可以正常工作,但觸摸發生時,高亮顯示操作(即觸摸時按鈕變暗)會丟失。有任何想法嗎?

+(void) styleButton:(UIButton*)button{ 
    UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(button.bounds.origin.x, button.bounds.origin.y, button.bounds.size.width, button.bounds.size.height)];  

    CALayer *sublayer = [CALayer layer]; 
    sublayer.shadowOffset = CGSizeMake(0, 3); 
    sublayer.shadowRadius = 5.0; 
    sublayer.shadowColor = [UIColor blackColor].CGColor; 
    sublayer.shadowOpacity = 0.8; 

    sublayer.frame = CGRectMake(button.bounds.origin.x, button.bounds.origin.y, button.bounds.size.width, button.bounds.size.height); 

    backgroundView.userInteractionEnabled = NO; 

    [backgroundView.layer addSublayer:sublayer]; 

    [button insertSubview:backgroundView atIndex:0]; 

    CALayer *imageLayer = [CALayer layer]; 
    imageLayer.frame = sublayer.bounds; 
    imageLayer.cornerRadius = 10.0; 
    imageLayer.contents = (id) [UIImage imageNamed:@"myImage.png"].CGImage; 
    imageLayer.cornerRadius = 5.0f; 
    imageLayer.masksToBounds = YES; 
    [sublayer addSublayer:imageLayer]; 
} 

回答

4

您是否嘗試過你的backgroundView轉換成一個UIImage並將其添加到按鈕而不是添加backgroundView作爲一個子視圖的?按下按鈕時,會保留變黑:

UIGraphicsBeginImageContext(backgroundView.frame.size); 
[backgroundView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
[button setImage:image forState:UIControlStateNormal]; 
+0

感謝。我會試試這個 –

0

像這樣(啓用ARC):

UIGraphicsBeginImageContextWithOptions(self.button.bounds.size, NO, [[UIScreen mainScreen] scale]); 

CGContextRef context = UIGraphicsGetCurrentContext(); 

for (UIView *aView in self.button.subviews) { 

    CGContextSaveGState(context); 
    CGContextTranslateCTM(context, aView.frame.origin.x, aView.frame.origin.y); 
    [aView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    CGContextRestoreGState(context); 
} 

UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 

UIGraphicsEndImageContext(); 

[self.button setImage:image forState:UIControlStateNormal]; 
[self.button.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)]; 
[self.button setAdjustsImageWhenHighlighted:YES];