ios - 在 UILabel 的特定字符后面画圈

标签 ios swift uilabel

我正在尝试在 UILabel 字符的特定部分后面绘制圆圈,而无需使用多个标签或重新计算帧。

我知道我可以使用属性文本将图像插入到 UILabel 中,但我希望圆圈位于数字(从 1 到 9)的后面。我不想存储 1 到 9 的图像。 我也找不到任何 pod 实现这一目标。

    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 条灰色)

最佳答案

我不明白你为什么不使用实时绘制圆圈中数字的实用函数。这样,您可以拥有任何您喜欢的数字字体、圆圈大小、数字颜色和圆圈颜色。例如:

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

关于ios - 在 UILabel 的特定字符后面画圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52410790/

相关文章:

swift - 用UILabel字母实现旋转、移动、缩放动画效果。 swift

ios - 在尚未加载的 VC 上使用委托(delegate)

iOS 核心数据数据保护不起作用

ios - 另一个 "could not dequeue a view of kind: UICollectionElementKindCell with identifier song"

swift - 如何列出对象符合的协议(protocol)?

Swift:理解指针

ios - 如何让 UILabel 在单词末尾显示 "..."而不是截断它?

ios - 根据 UISlider 值不断更新标签

ios - Swift Framework 仅在干净之后构建

ios - 导入 Swift 与导入基础