一個圓角 + 右上角刪除按鈕引發(fā)的血案!!!
1.一般方法實現(xiàn)圓角
UILabel *label = [UILabel new];
label.clipsToBounds = YES;
label.layer.cornerRadius = 5;
這樣實現(xiàn)圓角的方式有一個弊端,就是把一切超出父控件的部分剪切掉驶冒。一般情況下沈条,這也不算什么涕烧,但是仲翎,當(dāng)你添加的子控件需要顯示超出父控件的部分的時候,就顯示不出來湿镀,比如:添加一個右上角的刪除控件。
2.嘗試在當(dāng)前控件上添加圓角layer
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(40, 120, 80, 30)];
label.font = [UIFont systemFontOfSize: 20];
label.textColor = [UIColor blackColor];
label.text = @"Jashion";
[self.view addSubview: label];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect: label.bounds cornerRadius: 5];
CAShapeLayer *bgLayer = [CAShapeLayer layer];
bgLayer.frame = label.bounds;
bgLayer.path = path.CGPath;
bgLayer.fillColor = [UIColor orangeColor].CGColor;
[label.layer insertSublayer: bgLayer above: 0];
這樣會導(dǎo)致中文顯示正常绑青,英文被覆蓋的問題:
Label
什么原因?qū)е碌哪匕胤荆坎聹y是中文和英文的顯示有點區(qū)別弃理,具體打印一下它們的圖層結(jié)構(gòu),如下:
2個Label的圖層結(jié)構(gòu)
問題比較明了了,純英文和數(shù)字磁携,符號在label里顯示都是一個圖層顯示,而包含中文字符的會新生成一個UILabelContentLayer來承載內(nèi)容疑俭,所以哩照,中文可以顯示飘弧,而英文被覆蓋的原因在于学少,英文被子圖層直接覆蓋了,而中文添加的子圖層是在內(nèi)容顯示圖層的下面,所以不會被覆蓋健提。
ps:
1.UIButton和UILabel顯示中文和英文是一樣的
2.UILayerContentLayer永遠(yuǎn)都是在子圖層數(shù)組里最前面
3.換個思路学搜,一路死磕
既然直接添加圖層會覆蓋原有的圖層,設(shè)置圖層的zPosition也不行(因為沒有中文符號的label只有一個圖層恒水,沒有子圖層会放,添加一個新的圖層還是需要父圖層承載),這時候注意到設(shè)置原有圖層的背景顏色是不會覆蓋內(nèi)容顯示的钉凌,嘿嘿咧最。
直接上代碼:
UIImage *backgroundImage;
UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, [UIScreen mainScreen].scale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, backgroundColor.CGColor);
UIBezierPath *fillPath = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(borderWidth, borderWidth, self.frame.size.width - borderWidth, self.frame.size.height - borderWidth) cornerRadius: radius];
CGContextAddPath(context, fillPath.CGPath);
CGContextFillPath(context);
backgroundImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if (!backgroundImage) {
return;
}
self.layer.backgroundColor = [UIColor colorWithPatternImage: backgroundImage].CGColor; //注意這里不能直接設(shè)置self.backgroundColor,顯示會有問題御雕?矢沿??
完成的效果如下:
效果圖
總結(jié):
生活總是充滿驚喜酸纲,嘿嘿捣鲸,如果不是當(dāng)時公司項目需要實現(xiàn)這個效果,我現(xiàn)在都還不知道這些事情闽坡。意料之外栽惶,情理之中,挺好玩的疾嗅。