UILabel simple and efficient way to achieve rounded corners


We often meet such a demand, add tags to TableViewCell for example: hungry App in the shop will have, subtraction, special and new labels, these labels are generally used to achieve UILabel control, set the text, UILabel textColor, backgroundColor, and cornerRadius.

UILabel simple and efficient way to achieve rounded corners
hungry, sample.PNG?


This demand requires us to do round, industry also has a lot to do with rounded corners, the simplest is to set label.layer.cornerRadius = 2; label.layer.masksToBounds = YES; but to do so (label.layer.cornerRadius &gt 0; & & label.layer.masksToBounds = YES) will appear off screen rendering, for only a few pages to do round, it will not cause Carlton however, if each TableViewCell set some round, will make up a list of sliding Ming meal card.


The industry has many ways to optimize corners, you can search related articles. This article only for the UILabel cornerRadius way to explain. Let’s start with the cornerRadius property, which is the backgroundColor and border that affects the layer display, and doesn’t work on layer’s contents.

  • For the backgroundColor that does not need to set label, only sets the label of borderWidth and borderColor, sets the cornerRadius directly, and does not need to set masksToBounds = YES, so you can realize the rounding function.
  • At the same time the need for setting the label backgroundColor, set the cornerRadius directly is not normal to show the fillet, the reason is: UILabel set backgroundColor behavior, is no longer the background color set layer but contents set the background color. So the solution is that we don’t set the label of the backgroundColor, but we set the label.layer.backgroundColor directly so that you can set the cornerRadius separately and show the effect of fillet. Code: UILabel *tagLabel = [UILabel new]; tagLabel.text = @ “minus” tagLabel.textColor = [UIColor; tagLabel.font = whiteColor]; [UIFont = systemFontOfSize:12]; tagLabel.layer.backgroundColor [UIColor greenColor].CGColor; tagLabel.layer.cornerRadius = 2;

Reference article: four ways to set fillet in iOS