添加阴影的代码如下
//添加四边阴影效果
-(void)addFourSides:(UIView *)theView shadowWithColor:(UIColor*)theColor shadowOpacity:(CGFloat)shadowOpacity cornerRadius:(CGFloat)cornerRadius{
//阴影颜色
theView.layer.shadowColor = theColor.CGColor;
//阴影偏移
theView.layer.shadowOffset = CGSizeZero;
//阴影透明度,默认0
theView.layer.shadowOpacity = shadowOpacity;
//阴影半径,默认3
theView.layer.shadowRadius = cornerRadius;
theView.layer.masksToBounds = NO;
}
当view没有子控件的时候这样设置没问题
UIView *oneView = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
oneView.backgroundColor = [UIColor blackColor];
oneView.layer.cornerRadius = 10;
[self.view addSubview:oneView];
[self addFourSides:oneView shadowWithColor:[UIColor systemPinkColor] shadowOpacity:1 cornerRadius:3];
20201111-095043@2x.png
当有子view有需要设置圆角的时候就会出现问题,圆角不见了
UIView *oneView = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
oneView.backgroundColor = [UIColor blackColor];
oneView.layer.cornerRadius = 10;
[self.view addSubview:oneView];
[self addFourSides:oneView shadowWithColor:[UIColor systemPinkColor] shadowOpacity:1 cornerRadius:3];
UIView *subView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 100)];
subView1.backgroundColor = [UIColor yellowColor];
[oneView addSubview:subView1];
UIView *subView2 = [[UIView alloc]initWithFrame:CGRectMake(0, 100, 200, 100)];
subView2.backgroundColor = [UIColor blueColor];
[oneView addSubview:subView2];
20201111-100311@2x.png
但是当设置oneView.clipsToBounds = YES;时圆角没效果,
这是我们的处理方法是在oneView外层再套一个view,用oneView的superView设置阴影,oneView设置圆角,这样解决冲突问题.
UIView *superView = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
[self.view addSubview:superView];
[self addFourSides:superView shadowWithColor:[UIColor systemPinkColor] shadowOpacity:1 cornerRadius:5];
UIView *oneView = [[UIView alloc]initWithFrame:superView.bounds];
oneView.backgroundColor = [UIColor blackColor];
oneView.layer.cornerRadius = 20;
oneView.clipsToBounds = YES;
[superView addSubview:oneView];
UIView *subView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 100)];
subView1.backgroundColor = [UIColor yellowColor];
[oneView addSubview:subView1];
UIView *subView2 = [[UIView alloc]initWithFrame:CGRectMake(0, 100, 200, 100)];
subView2.backgroundColor = [UIColor blueColor];
[oneView addSubview:subView2];
20201111-101630@2x.png
还有一种方法就是单独设置subView的圆角,如:设置subView1的上左,上右圆角,subView2的下左,下右圆角
但是相对的没有直接外层加个view来得简单,粗暴!
网友评论