30

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?

Hitesh
  • 896
  • 1
  • 9
  • 22
A_G
  • 2,260
  • 3
  • 23
  • 56
  • 5
    Possible duplicate of [How do I make an UIImage/-View with rounded corners CGRect (Swift)](https://stackoverflow.com/questions/25476139/how-do-i-make-an-uiimage-view-with-rounded-corners-cgrect-swift) – mag_zbc Sep 07 '17 at 07:49

5 Answers5

84

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

textLabel?.layer.masksToBounds = true
Son Pham
  • 1,516
  • 1
  • 14
  • 22
12

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
Pushpendra
  • 976
  • 6
  • 13
  • the questioner already mentioned the size `layer.cornerRadius = 20.0` – Anbu.Karthik Sep 07 '17 at 07:44
  • it is for when you want to accurate corners then use this. if size if greater then height then it will not resize in perfect shape. or you can use constant value as you needed. – Pushpendra Sep 07 '17 at 07:47
12

swift 4.2

set label corner radius. Its working fine......

labelVerified.layer.cornerRadius = 6
labelVerified.layer.masksToBounds = true
Srinivasan_iOS
  • 972
  • 10
  • 12
8

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.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
3

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.

Leonardo
  • 218
  • 4
  • 17