Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS label in a circle

Tags:

ios

swift

swift3

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.

enter image description here.

however the above doesn't output the orange colors. why ?

like image 266
Aboogie Avatar asked Nov 16 '16 12:11

Aboogie


2 Answers

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
like image 94
vaibhav Avatar answered Oct 20 '22 22:10

vaibhav


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:

enter image description here

like image 4
vikingosegundo Avatar answered Oct 20 '22 22:10

vikingosegundo