Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounded corners of UILabel swift

Tags:

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?

like image 626
Astha Gupta Avatar asked Sep 07 '17 07:09

Astha Gupta


People also ask

How do you round the corners of a label in Swift?

masksToBounds = true" is an important code, if you apply corner radius to a label and if it dosen't work than adding this will definitely add the corner radius to a particular label.. So this should be the correct answer..

How do I add padding to UILabel Swift?

If you have created an UILabel programmatically, replace the UILabel class with the PaddingLabel and add the padding: // Init Label let label = PaddingLabel() label. backgroundColor = . black label.

What is corner radius?

The corner radius is a measurement describing the curve on the corners of your labels. This is measured in millimetres and refers to the radius of the circle created if the curve was extended to create a full circle.


2 Answers

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

textLabel?.layer.masksToBounds = true
like image 90
Son Pham Avatar answered Oct 13 '22 12:10

Son Pham


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
like image 27
Pushpendra Avatar answered Oct 13 '22 13:10

Pushpendra