扩展名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
}
基本上文字不再居中。如果注释掉图像的代码,则标签文本完全居中。
我传递了一张图片和一根字符串" 20"在数组中使用此方法。