【问题标题】:Adding a badge to the round button - Swift向圆形按钮添加徽章 - Swift
【发布时间】:2020-11-03 16:26:08
【问题描述】:

我想将下方的红点作为徽章始终位于按钮的右上角。

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

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

我该怎么做?

【问题讨论】:

  • 对不起,我添加了图片

标签: swift button rounded-corners badge


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您可以使用约束将视图与超级视图的右上角对齐。将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)
    

    【讨论】:

      猜你喜欢
      • 2012-05-04
      • 2016-03-21
      • 1970-01-01
      • 2014-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多