添加陰影的代碼如下
//添加四邊陰影效果
-(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];
當有子view有需要設置圓角的時候就會出現(xiàn)問題,圓角不見了
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];
但是當設置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];
還有一種方法就是單獨設置subView的圓角,如:設置subView1的上左,上右圓角,subView2的下左,下右圓角
但是相對的沒有直接外層加個view來得簡單,粗暴!