UIView with rounded corners and drop shadow?

前端 未结 30 2989
一整个雨季
一整个雨季 2020-11-22 08:00

I’ve been working on an application for a couple of years and received a simple design request: Round the corners on a UIView and add a drop shadow.To do as given below.

30条回答
  •  轮回少年
    2020-11-22 08:18

    daniel.gindi's answer above did the trick for me! (+1 daniel) However, I had to make minor adjustments - change the shadowFrame size to be same as view's frame size, and enable user interaction. Here's the updated code:

    + (UIView*)putView:(UIView*)view insideShadowWithColor:(UIColor*)color andRadius:(CGFloat)shadowRadius andOffset:(CGSize)shadowOffset andOpacity:(CGFloat)shadowOpacity
    {
        CGRect shadowFrame; // Modify this if needed
    
        // Modified this line
        shadowFrame.size = CGSizeMake(view.frame.size.width, view.frame.size.height);
    
        shadowFrame.origin.x = 0.f;
        shadowFrame.origin.y = 0.f;
        UIView * shadow = [[UIView alloc] initWithFrame:shadowFrame];
    
        // Modified this line
        shadow.userInteractionEnabled = YES;
        shadow.layer.shadowColor = color.CGColor;
        shadow.layer.shadowOffset = shadowOffset;
        shadow.layer.shadowRadius = shadowRadius;
        shadow.layer.masksToBounds = NO;
        shadow.clipsToBounds = NO;
        shadow.layer.shadowOpacity = shadowOpacity;
    
        [shadow addSubview:view];
        return shadow;
    }
    

    I would like to add that in my case, I was trying to add this to a 3rd party view controller, i.e. I did not have direct control over the code. So, here's how I used the function above:

    UIView *shadow = [self putView:vc.view 
             insideShadowWithColor:[UIColor blackColor]
                         andRadius:5.0 
                         andOffset:CGSizeMake(0.0, 0.0) 
                        andOpacity:1.0];
    vc.view = shadow;
    vc.view.layer.cornerRadius = 5.0;
    vc.view.layer.masksToBounds = YES;
    

提交回复
热议问题