Rounded corners of UILabel swift

29.5k views Asked by At

I am creating a UILabel programatically. But the below piece of code doesn't give me rounded corners. I think I am missing out something very basic.

var textLabel:UILabel? =  UILabel()
textLabel?.text = text
textLabel?.frame = CGRect(x:point.x, y:point.y, width:(textLabel?.intrinsicContentSize.width)!, height:15)
textLabel?.backgroundColor = UIColor.white
textLabel?.font = UIFont(name:"OpenSans", size:8)
textLabel?.sizeToFit()
textLabel?.layer.cornerRadius = 20.0

Can anyone please point me in the right direction?

5

There are 5 answers

0
Son Pham On BEST ANSWER

I think you should set maskToBounds for textLabel. try this:

textLabel?.layer.masksToBounds = true
0
Anbu.Karthik On

set masksToBounds for your label

masksToBounds act as a Boolean indicating whether sublayers are clipped to the layer’s bounds.

textLabel?.layer.cornerRadius = 20.0
textLabel?.layer.masksToBounds = true

refer apple documents.

0
Leonardo On

try this :

yourLabel.layer.cornerRadius = 8.0
yourLabel.layer.masksToBounds = true
yourLabel.layer.borderColor = UIColor.white.cgColor
yourLabel.layer.borderWidth = 1.0

this should give you the rounded borders

The key is the property "maskToBounds" that is a Boolean indicating whether sublayers are clipped to the layer’s bounds.

2
Pushpendra On

try this :-

textLabel?.layer.cornerRadius = textLabel?.frame.size.height/2.0

textLabel?.layer.masksToBounds = true

if you want to set border color then :-

  textLabel?.layer.borderColor = .red.cgColor
  textLabel?.layer.borderWidth = 1.0
0
Srinivasan_iOS On

swift 4.2

set label corner radius. Try this.....

labelVerified.layer.cornerRadius = 6
labelVerified.layer.masksToBounds = true