在UILabel的特定字符后面绘制圆圈

时间:2018-09-19 16:53:40

标签: ios swift uilabel

我试图在UILabel字符的特定部分后面绘制圆圈,而不必使用多个标签或重新计算框架。

我知道我可以使用属性文本将图像插入UILabel,但是我希望圆圈位于数字后面(从1到9)。我不想存储1到9的图像。 我也找不到任何能做到这一点的吊舱。

    let fullText = NSMutableAttributedString()

    let imageAttachment = NSTextAttachment()
    imageAttachment.image = UIImage(named: "\(number)_\(color == .yellow ? "yellow" : "gray")")
    let imageString = NSAttributedString(attachment: imageAttachment)
    let endString = NSAttributedString("nouveaux")

    fullString.append(imageString)
    fullString.append(endString)

    mainLabel.attributedText = fullString

enter image description here

编辑

我想在字符串的每个数字后面绘制圆圈。 我希望它成为通用工具,如果可能的话,某种解析器返回属性字符串,否则返回唯一的UIView。 另一个用例是“ 4条消息|聊天2” (4为黄色,2为灰色)

2 个答案:

答案 0 :(得分:2)

我不明白为什么您不只是使用实用程序功能来实时绘制圆形数字。这样,您可以拥有自己喜欢的任何数字字体,圆圈大小,数字颜色和圆圈颜色。例如:

func circleAroundDigit(_ num:Int, circleColor:UIColor,
                       digitColor:UIColor, diameter:CGFloat,
                       font:UIFont) -> UIImage {
    precondition((0...9).contains(num), "digit is not a digit")
    let p = NSMutableParagraphStyle()
    p.alignment = .center
    let s = NSAttributedString(string: String(num), attributes:
        [.font:font, .foregroundColor:digitColor, .paragraphStyle:p])
    let r = UIGraphicsImageRenderer(size: CGSize(width:diameter, height:diameter))
    return r.image {con in
        circleColor.setFill()
        con.cgContext.fillEllipse(in:
            CGRect(x: 0, y: 0, width: diameter, height: diameter))
        s.draw(in: CGRect(x: 0, y: diameter / 2 - font.lineHeight / 2,
                          width: diameter, height: diameter))
    }
}

这里是使用方法:

let im = circleAroundDigit(3, circleColor: .yellow, 
    digitColor: .white, diameter: 30, font:UIFont(name: "GillSans", size: 20)!)

这是结果图像;但是请注意,仅通过以不同的方式调用该函数即可调整此方面的所有方面:

enter image description here

好的,现在您有了一张图片。您说您已经知道如何将图像内联插入属性字符串中并将其显示为标签的一部分,所以我不会解释如何做到这一点:

enter image description here

答案 1 :(得分:1)

使用UIStackView,这很简单,设置彩色视图层的角半径…

结果…

或在外部堆栈视图中具有2个堆栈视图≥

结果…

相关问题