【问题标题】:Show Highlight on a UIButton with Subview在带有子视图的 UIButton 上显示突出显示
【发布时间】:2011-10-26 04:43:43
【问题描述】:

我正在尝试创建一个具有以下特征的 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];
}

【问题讨论】:

    标签: ios uiview uibutton calayer


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      像这样(启用 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];
      

      【讨论】:

        猜你喜欢
        • 2016-03-19
        • 2013-10-15
        • 1970-01-01
        • 2015-07-21
        • 2012-04-22
        • 2015-06-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多