button圆角高效设置

需求
我们会经常遇到这样一个需求,给TableViewCell添加标签,例如:饿了么App中店铺会有,减、特、新等标签,这些标签一般都是用UILabel控件实现,UILabel中设置text,textColor,backgroundColor,以及cornerRadius。


button圆角高效设置_第1张图片

饿了么示例.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;

参考文章:iOS设置圆角的四种方法

你可能感兴趣的:(button圆角高效设置)