控件添加陰影

添加陰影的代碼如下

//添加四邊陰影效果
-(void)addFourSides:(UIView *)theView shadowWithColor:(UIColor*)theColor shadowOpacity:(CGFloat)shadowOpacity cornerRadius:(CGFloat)cornerRadius{
    //陰影顏色
    theView.layer.shadowColor = theColor.CGColor;
    //陰影偏移
    theView.layer.shadowOffset = CGSizeZero;
    //陰影透明度,默認(rèn)0
    theView.layer.shadowOpacity = shadowOpacity;
    //陰影半徑,默認(rèn)3
    theView.layer.shadowRadius = cornerRadius;
    
    theView.layer.masksToBounds = NO;
}

當(dāng)view沒有子控件的時候這樣設(shè)置沒問題

    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

當(dāng)有子view有需要設(shè)置圓角的時候就會出現(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];
20201111-100311@2x.png

但是當(dāng)設(shè)置oneView.clipsToBounds = YES;時圓角沒效果,

這是我們的處理方法是在oneView外層再套一個view,用oneView的superView設(shè)置陰影,oneView設(shè)置圓角,這樣解決沖突問題.

    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

還有一種方法就是單獨(dú)設(shè)置subView的圓角,如:設(shè)置subView1的上左,上右圓角,subView2的下左,下右圓角
但是相對的沒有直接外層加個view來得簡單,粗暴!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容