Hi I am trying to draw a circle by using the layer for UILabel however, my label only shows the number not the background color or border that I have created for the label. why is this ? This is my code :
let countLabel = UILabel()
countLabel.text = "5"
let size:CGFloat = 55.0
countLabel.textColor = UIColor.white
countLabel.textAlignment = .center
countLabel.font = UIFont.systemFont(ofSize: 14.0)
countLabel.bounds = CGRect(x : 0.0,y : 0.0,width : size, height : size)
countLabel.layer.cornerRadius = size / 2
countLabel.layer.borderWidth = 3.0
//countLabel.layer.masksToBounds = true
countLabel.layer.backgroundColor = UIColor.orange.cgColor
countLabel.layer.borderColor = UIColor.orange.cgColor
countLabel.center = CGPoint(x:200.0,y: 200.0)
countLabel.translatesAutoresizingMaskIntoConstraints = false
self.topContainer.addSubview(countLabel)
countLabel.topAnchor.constraint(equalTo: profileImage.topAnchor).isActive = true
countLabel.trailingAnchor.constraint(equalTo: profileImage.trailingAnchor, constant: 10).isActive = true
I want to get something like this.
.
however the above doesn't output the orange colors. why ?
Try adding below code:
countLabel.layer.cornerRadius = 0.5 * countLabel.bounds.size.width
Instead of:
// remove the below code of line from your code
countLabel.layer.cornerRadius = size / 2
I guess you stumbled upon an bug here.
If I add a code base on your code into a playground, it outputs "empty image" instead of showing the view.
But if I create the label with a frame, it works.
Not working:
let countLabel = UILabel()
countLabel.frame = CGRect(x : 0.0,y : 0.0,width : size, height : size)
Not working:
let countLabel = UILabel()
countLabel.bounds = CGRect(x : 0.0,y : 0.0,width : size, height : size)
Not working:
let countLabel = UILabel()
countLabel.sizeToFit()
Working:
let size:CGFloat = 55.0
let countLabel = UILabel(frame: CGRect(x : 0.0,y : 0.0,width : size, height : size))
Full code from my playground:
import UIKit
let size:CGFloat = 55.0
let countLabel = UILabel(frame: CGRect(x : 0.0,y : 0.0,width : size, height : size))
countLabel.text = "5"
countLabel.textColor = UIColor.white
countLabel.textAlignment = .center
countLabel.font = UIFont.systemFont(ofSize: 24.0)
countLabel.layer.cornerRadius = size / 2
countLabel.layer.borderWidth = 3.0
countLabel.layer.masksToBounds = true
countLabel.layer.backgroundColor = UIColor.orange.cgColor
countLabel.layer.borderColor = UIColor.orange.cgColor
countLabel.translatesAutoresizingMaskIntoConstraints = false
result:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With