Search code examples
swiftbuttonrounded-cornersbadge

Adding a badge to the round button - Swift


I would like to position the red dot below as the badge always to the top right of the button.

let badgeView = UIButton (frame: CGRect (x: 20, y: 40, width: 16, height: 16))
self.addsubview (badgeview)

With this code, the result is like this and is erroneous:

enter image description here

How can I do that?


Solution

  • You can use constraints to align a view to superview's top right. Add a badgeView to a UIButton like below. You can play with constants.

    // your button
    let buttonSize: CGFloat = 50
    let button = UIButton(frame: CGRect(x: 0, y: 0, width: buttonSize, height: buttonSize))
    button.layer.backgroundColor = UIColor.black.cgColor
    button.layer.cornerRadius = buttonSize / 2
    
    // your badge view (use UIView instead of UIButton)
    let badgeSize: CGFloat = 16
    let badgeView = UIView()
    badgeView.backgroundColor = UIColor(red: 235/255, green: 68/255, blue: 90/255, alpha: 1)
    badgeView.layer.cornerRadius = badgeSize / 2
    button.addSubview(badgeView)
    
    // set constraints
    badgeView.translatesAutoresizingMaskIntoConstraints = false
    let constraints: [NSLayoutConstraint] = [
        badgeView.rightAnchor.constraint(equalTo: button.rightAnchor, constant: -4),
        badgeView.topAnchor.constraint(equalTo: button.topAnchor, constant: 0),
        badgeView.widthAnchor.constraint(equalToConstant: badgeSize),
        badgeView.heightAnchor.constraint(equalToConstant: badgeSize)
    ]
    NSLayoutConstraint.activate(constraints)
    

    enter image description here