Search code examples
iosswiftuilabelbadge

adding dot on top right corner on label


Hello i am creating swift app and i am want to add red dot on UILabel but i can't find solution how to do that i want output like below

i want to achive something like this

i have check many solution but that all if for UIButton but i need to implement on UILabel i have refer This

can any one have any solution for this than kindly help me


Solution

  • Try this

    func addlabelBadge(label:UILabel,text:String,fontSize:CGFloat = 17.0) {
            let size: CGSize = text.size(withAttributes: [.font: UIFont.systemFont(ofSize: fontSize)])
            let point = CGPoint(x: size.width, y: 0)
    
            let circle = CAShapeLayer()
            let path = UIBezierPath(arcCenter: CGPoint(x: point.x+5, y: 10), radius: 5, startAngle: 0, endAngle: .pi*2, clockwise: true)
            circle.path = path.cgPath
            circle.fillColor = UIColor.red.cgColor
            label.layer.addSublayer(circle)
        }
    

    call this function at viewDidLayoutSubviews

    override func viewDidLayoutSubviews() {
        addlabelBadge(label: myLabel,text:"Badges")
    
    }
    

    or You call this function on button tap

    @objc func didClickedMyButton(){
            addlabelBadge(label: myLabel,text:"Badges")
            view.layoutIfNeeded()
    }
    

    you can remove the dot calling

    myLabel.layer.sublayers?.removeAll()
    view.layoutIfNeeded()
    

    Result