UIView同时设置圆角与阴影

设置圆角使用的的masksToBounds=YES与阴影中的clipsToBounds=NO会产生冲突,无法同时使用,否则会不生效。

解决办法:现在新建一个单独的UIView在下层作为阴影,上层原来的UIView设置圆角。

- (void)addToast:(NSString *)string {
    UIView *shadowView = [UIView new];
    [kKeyWindow addSubview:shadowView];
    [shadowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-250);
        make.centerX.mas_equalTo(kKeyWindow);
        make.width.mas_equalTo(118);
        make.height.mas_equalTo(42);
    }];
    shadowView.backgroundColor = [UIColor whiteColor];
    //增加阴影
    [self addShadowForView:shadowView shadowColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.1]];
    
    UILabel *toast = [UILabel new];
    [shadowView addSubview:toast];
    [toast mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.mas_equalTo(0);
    }];
    
    toast.backgroundColor = kWhiteColor;
    toast.text = string;
    toast.textColor = HexColor(@"#252525");
    toast.font = [UIFont systemFontOfSize:15];
    [toast.layer setCornerRadius:12];
    [toast.layer setMasksToBounds:YES]
    toast.textAlignment = NSTextAlignmentCenter;
    
    [UIView animateWithDuration:0.2 delay:1.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        shadowView.alpha = 0;
    } completion:^(BOOL finished) {
        [shadowView removeFromSuperview];
    }];
}

- (void)addShadowForView:(UIView *)view shadowColor:(UIColor *)shadowColor {
    view.layer.shadowColor = shadowColor.CGColor;
    view.layer.shadowOffset = CGSizeMake(0, 0);
    view.layer.shadowOpacity = 1.0;
    view.layer.shadowRadius = 12;
    view.layer.cornerRadius = 12;
}

你可能感兴趣的:(ios,xcode,objective-c,阴影,圆角)