iOS徽章就像UILabel一样

时间:2015-01-27 13:40:45

标签: ios iphone xcode swift

请帮我制作像UILabel这样的简单徽章。

我的代码是:

let badgeLabel = UILabel(frame: CGRectMake(0, 0, 25, 25))
badgeLabel.backgroundColor = UIColor.clearColor()
badgeLabel.layer.backgroundColor = UIColor.redColor().CGColor
badgeLabel.layer.cornerRadius = 25/2
badgeLabel.layer.borderWidth = 3.0
badgeLabel.layer.borderColor = UIColor.whiteColor().CGColor

结果我在白色边框上有一个小红色笔划的UILabel:

enter image description here

enter image description here

3 个答案:

答案 0 :(得分:1)

试试这个。

let badgeLabel = UILabel(frame: CGRectMake(0, 0, 25, 25)) badgeLabel.backgroundColor = UIColor.redColor() badgeLabel.layer.backgroundColor = UIColor.clearColor().CGColor badgeLabel.layer.cornerRadius = 25/2 badgeLabel.layer.borderWidth = 3.0 badgeLabel.layer.borderColor = UIColor.whiteColor().CGColor

答案 1 :(得分:0)

嘿检查这个最新的代码,确定它会起作用。

let roundRing = UILabel(frame: badgeLabel.frame)
    roundRing.backgroundColor = UIColor.clearColor()
    roundRing.layer.backgroundColor = UIColor.whiteColor().CGColor
    roundRing.layer.cornerRadius = 25/2
    roundRing.layer.borderWidth = 3.0
    roundRing.layer.borderColor = UIColor.whiteColor().CGColor
    self.view .addSubview(roundRing)

    let innerRegion = UILabel(frame: CGRectMake(3, 3, 19, 19))
    innerRegion.backgroundColor = UIColor.clearColor()
    innerRegion.layer.backgroundColor = UIColor.redColor().CGColor
    innerRegion.layer.cornerRadius = 19/2
    innerRegion.text="2"
    innerRegion.font=UIFont(name: "MarkerFelt-Thin", size: 10)!
    innerRegion.textAlignment=NSTextAlignment.Center
    roundRing.addSubview(innerRegion)

enter image description here

答案 2 :(得分:0)

你缺少maskToBounds

适用于swift 3:

let badgeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
badgeLabel.backgroundColor = .red
badgeLabel.layer.cornerRadius = 25/2
badgeLabel.layer.masksToBounds = true
badgeLabel.layer.borderWidth = 3.0
badgeLabel.layer.borderColor = .white