将图像添加到NSAttributedString使文本不居中

时间:2017-08-31 18:27:49

标签: ios swift nsattributedstring

扩展名UILabel {

func setAttributedTextWithElements(objectsForLabel: [AnyObject]) {

    let attributedString = NSMutableAttributedString()
    for object in objectsForLabel {

        if let string = object as? String {
            attributedString.append(NSAttributedString.init(string: string))
        } else if let imageForLabel = object as? UIImage {
            let attachment = NSTextAttachment()
            attachment.image = imageForLabel
            let attributedImageString = NSAttributedString.init(attachment: attachment)
            attributedString.append(attributedImageString)
            let imageWidth = (attachment.image?.size.width)!
            let imageHeight = (attachment.image?.size.height)!
            attachment.bounds = CGRect(x: 0, y: font.descender, width:imageWidth, height:imageHeight)
        }
    }
    attributedText = attributedString
}

enter image description here

基本上文字不再居中。如果注释掉图像的代码,则标签文本完全居中。

我传递了一张图片和一根字符串" 20"在数组中使用此方法。

0 个答案:

没有答案