UILabel簡單高效實現圓角的方式
阿新 • • 發佈:2019-02-13
需求
我們會經常遇到這樣一個需求,給TableViewCell新增標籤,例如:餓了麼App中店鋪會有,減、特、新等標籤,這些標籤一般都是用UILabel控制元件實現,UILabel中設定text,textColor,backgroundColor,以及cornerRadius。
餓了麼示例.PNG
問題
這個需求要求我們做圓角,業界也有很多做圓角的方式,最簡單的就是設定label.layer.cornerRadius = 2; label.layer.masksToBounds = YES; 但是這樣做(label.layer.cornerRadius > 0 && label.layer.masksToBounds = YES)會出現離屏渲染,對於頁面中只有少量需要做圓角,也不會造成卡頓,但是如果是每個TableViewCell設定一些圓角,就會使列表滑動起來有明顯示卡頓。
解決方法
業界對於圓角優化很多方式,大家可以搜一下相關文章。本文只針對UILabel的cornerRadius方式進行講解。先說一下cornerRadius屬性,它是影響layer顯示的backgroundColor和border,對layer的contents不起作用。
- 對於不需要設定label的backgroundColor,只設置borderWidth、borderColor的label,直接設定cornerRadius,不需要設定masksToBounds = YES,就可以實現圓角功能。
- 對於需要同時設定label的backgroundColor時,直接設定cornerRadius是不能正常顯示圓角的,原因是:UILabel設定backgroundColor的行為,不再是設定layer的背景色而是為contents設定背景色。所以解決方式是我們不去設定label的backgroundColor,而是直接設定label.layer.backgroundColor,這樣就可以實現單獨設定cornerRadius,顯示圓角的效果。程式碼:
UILabel *tagLabel = [UILabel new]; tagLabel.text = @"減"; tagLabel.textColor = [UIColor whiteColor]; tagLabel.font = [UIFont systemFontOfSize:12]; tagLabel.layer.backgroundColor = [UIColor greenColor].CGColor; tagLabel.layer.cornerRadius = 2;