Rounded corners of UILabel swift
Asked Answered
Q

5

31

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?

Quadrille answered 7/9, 2017 at 7:29 Comment(1)
Possible duplicate of How do I make an UIImage/-View with rounded corners CGRect (Swift)Fante
D
89

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

textLabel?.layer.masksToBounds = true
Duce answered 7/9, 2017 at 7:49 Comment(0)
C
13

swift 4.2

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

labelVerified.layer.cornerRadius = 6
labelVerified.layer.masksToBounds = true
Compendious answered 11/5, 2019 at 9:39 Comment(0)
H
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
Hendrika answered 7/9, 2017 at 7:42 Comment(2)
the questioner already mentioned the size layer.cornerRadius = 20.0Cowpuncher
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.Hendrika
C
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.

Cowpuncher answered 7/9, 2017 at 7:30 Comment(0)
C
4

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.

Chicken answered 7/9, 2017 at 7:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.