中心NSAttributed字符串以图像NSTextAttachment

时间:2018-12-24 02:05:27

标签: swift4

我有一个NSMutableAttributedString字符串和一个NSTextAttachment()图像。

文本显示在图像的底部。有没有办法使文本在图像中居中?

    let fullString = NSMutableAttributedString(string: "Acceptance")
    let image1 = NSTextAttachment()
    image1.image = UIImage(named: "pos")

    image1.setImageHeight(height:30)

    let image1String = NSAttributedString(attachment: image1)

    fullString.append(image1String)

我确实有一个NSTextAttachment扩展名,用于按比例缩小图像,并且对文本为何居中不起作用

extension NSTextAttachment {
func setImageHeight(height: CGFloat) {
    guard let image = image else { return }
    let ratio = image.size.width / image.size.height

    bounds = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: ratio * height, height: height)
}
}

这是它的样子

enter image description here

编辑:我明白了。我将其包括在内,因为它可以在将来帮助其他人。

image1.bounds = CGRect(x: 0, y: -10, width: 35, height: 35)

0 个答案:

没有答案
相关问题