简体   繁体   中英

Rounded corners of UILabel swift

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?

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

textLabel?.layer.masksToBounds = true

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

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 .

swift 4.2

set label corner radius and working fine

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM