在具有子视图的UIButton上显示突出显示

时间:2011-10-26 04:43:44

标签: ios uiview uibutton calayer

我正在尝试创建一个具有以下特征的UI按钮: *自定义图像作为其内容 *圆角 *投影

使用以下代码将格式化按钮以正确显示并起作用,但是当触摸发生时,高亮操作(即,触摸时按钮变暗)将丢失。有什么想法吗?

+(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];
}

2 个答案:

答案 0 :(得分:4)

您是否尝试将backgroundView转换为UIImage并将其添加到按钮而不是将backgroundView添加为子视图?这样可以在按下按钮时保持变暗:

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

答案 1 :(得分: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];