为圆形按钮添加徽章 - Swift

Adding a badge to the round button - Swift

我想将下面的红点作为徽章放置在按钮的右上角。

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

用这段代码,结果是这样的,是错误的:

我该怎么做?

如果徽章和徽章所在的按钮的大小都不变,徽章的框架应该是:

CGRect(x: radius * cos45 + radius, y: radius - radius * cos45, width: 0, height: 0).insetBy(dx: -8, dy: -8)

其中cos45sqrt(2) / 2radius是黑色按钮的半径。这将以按钮的圆周为中心绘制徽章。

let cos45 = sqrt(2) / 2
let badgeView = UIButton (frame: CGRect(x: radius * cos45 + radius, y: radius - radius * cos45, width: 0, height: 0).insetBy(dx: -8, dy: -8))
// make badgeView look pretty...
self.addSubview (badgeview)

我觉得使用 UIButton 作为徽章有点奇怪,除非点击徽章与点击按钮的效果不同。否则你可以只使用常规 UIView

您可以使用约束将视图与父视图的右上角对齐。将 badgeView 添加到 UIButton,如下所示。你可以玩常量。

// 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)