Как центрировать изображение в атрибутивной строке?

У меня есть image что я хочу центрировать рядом с кучей текста, но даже когда я установил NSMutableParagraphStylealignment в centerлиния с изображением не центрируется

Если бы кто-нибудь мог помочь мне отцентрировать линию с изображением (т.е. первой строкой), это было бы здорово!

Код

let text = " text next to image is not centered \n\n centered text \n more centered text"
let iconAttachment = textAttachment(fontSize: 14, image: #imageLiteral(resourceName: "icon"))
        let iconString = NSAttributedString(attachment: iconAttachment)
let style = NSMutableParagraphStyle()
        style.alignment = .center
        style.minimumLineHeight = 20

        let attributedText = NSMutableAttributedString()
        attributedText.append(iconString)
        let fullText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName : style])
        attributedText.append(fullText)

private func textAttachment(fontSize: CGFloat, image: UIImage) -> NSTextAttachment {
        let font = UIFont.systemFont(ofSize: fontSize) //set accordingly to your font, you might pass it in the function
        let textAttachment = NSTextAttachment()
            textAttachment.image = image
        let mid = font.descender + font.capHeight
        textAttachment.bounds = CGRect(x: 0, y: font.descender - image.size.height / 2 + mid + 2, width: image.size.width, height: image.size.height).integral
        return textAttachment
    }

3 ответа

Решение

Вам просто нужно выровнять текст lebel по центру, и он будет работать:

 label.textAlignment = .center

введите описание изображения здесь

Вот код для достижения желаемого изображения в центре.

    let text = "\ntext next to image is not centered \n\n centered text \n more centered text"
    let iconAttachment = textAttachment(fontSize: 5, image: #imageLiteral(resourceName: "eye"))
    let iconString = NSAttributedString(attachment: iconAttachment)
    let style = NSMutableParagraphStyle()
    style.alignment = .center
    style.minimumLineHeight = 20

    let attributedText = NSMutableAttributedString()
    attributedText.append(iconString)
    let fullText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName : style])
    attributedText.append(fullText)
    lbl.attributedText = attributedText;
    lbl.numberOfLines = 0
    lbl.lineBreakMode = .byWordWrapping
    lbl.textAlignment = .center

Выход

Примечание: без изменений в функции

введите описание изображения здесь

Вы должны использовать .baselineOffset. В зависимости от размера вашего шрифта смещение может варьироваться.

      let image = NSImage(imageLiteralResourceName: "snail")
let attachment = NSTextAttachment()
attachment.image = image
let mutableAttributedString = NSMutableAttributedString(attachment: attachment)
mutableAttributedString.addAttributes([.baselineOffset : -2], range: NSRange(location: 0, length: mutableAttributedString.length))
mutableAttributedString.append(NSAttributedString(string: " Hello World!"))

label.attributedStringValue = mutableAttributedString

Результат:

Другие вопросы по тегам