0

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

David
  • 13
  • 2
  • could you please share your code? we need to know what you've done before – emrcftci May 12 '20 at 07:36
  • You can subclass a UILabel and then create your own layout. Basically create a Swift file that inherits from UILabel and add visual element with code or make it in a .xib file. If you are unfamiliar with writing the code layout just use the interface builder to make your label. – andromedainiative May 12 '20 at 07:39

1 Answers1

1

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

Dilan
  • 2,610
  • 7
  • 23
  • 33
  • Thank you! this helpful to me but i want red do right after last letter like "Badge" than i want dot after "e" and if now i change "Badge" to "Badges" than i want dot after "s" please help me out – David May 12 '20 at 08:55
  • Okay Thank you ! – David May 12 '20 at 09:01
  • @David check the updated answer. You need to calculate the text length and get a point.then you can draw the dot using that point. make sure match the function font size to your label font size – Dilan May 12 '20 at 09:14
  • Thank You Very Much its Work Like Charm For me! – David May 12 '20 at 09:45