对齐 NSAttributed 文本中的图像和文本
Align the image and text in NSAttributed text
我需要水平对齐图像和文本并将该字符串分配给 UILabel。下面是我的代码:
let attachment = NSTextAttachment()
let text = "Current user."
attachment.image = UIImage(named: "icon-horizontal-line")
let attachmentString = NSAttributedString(attachment: attachment)
let mutableAttributedString = NSMutableAttributedString()
mutableAttributedString.append(attachmentString)
let string = NSMutableAttributedString(string: text, attributes: [:])
mutableAttributedString.append(string)
label.attributedText = mutableAttributedString
我的结果是这样的:
我希望图像和字符串都对齐类似于:----- 当前用户。
您需要设置附件的边界。这是您更新后的代码。
let attachment = NSTextAttachment()
let text = "Current user."
let img = UIImage(named: "icon-horizontal-line")
let font = UIFont.systemFont(ofSize: 18)
attachment.image = img
let mid = font.descender + font.capHeight
attachment.bounds = CGRect(x: 0, y: font.descender - img!.size.height / 2 + mid + 2, width: img!.size.width, height: img!.size.height)
let attachmentString = NSAttributedString(attachment: attachment)
let mutableAttributedString = NSMutableAttributedString()
mutableAttributedString.append(attachmentString)
let string = NSMutableAttributedString(string: text, attributes: [:])
mutableAttributedString.append(string)
label.attributedText = mutableAttributedString
我需要水平对齐图像和文本并将该字符串分配给 UILabel。下面是我的代码:
let attachment = NSTextAttachment()
let text = "Current user."
attachment.image = UIImage(named: "icon-horizontal-line")
let attachmentString = NSAttributedString(attachment: attachment)
let mutableAttributedString = NSMutableAttributedString()
mutableAttributedString.append(attachmentString)
let string = NSMutableAttributedString(string: text, attributes: [:])
mutableAttributedString.append(string)
label.attributedText = mutableAttributedString
我的结果是这样的:
我希望图像和字符串都对齐类似于:----- 当前用户。
您需要设置附件的边界。这是您更新后的代码。
let attachment = NSTextAttachment()
let text = "Current user."
let img = UIImage(named: "icon-horizontal-line")
let font = UIFont.systemFont(ofSize: 18)
attachment.image = img
let mid = font.descender + font.capHeight
attachment.bounds = CGRect(x: 0, y: font.descender - img!.size.height / 2 + mid + 2, width: img!.size.width, height: img!.size.height)
let attachmentString = NSAttributedString(attachment: attachment)
let mutableAttributedString = NSMutableAttributedString()
mutableAttributedString.append(attachmentString)
let string = NSMutableAttributedString(string: text, attributes: [:])
mutableAttributedString.append(string)
label.attributedText = mutableAttributedString