如何将图像置于属性字符串中?

时间:2017-07-07 05:48:07

标签: ios nsattributedstring nsparagraphstyle

我有一个image,我希望将其放在一堆文本旁边,但即使我将NSMutableParagraphStyle alignment设置为center,图像的行也会不是中心

enter image description here

如果有人能帮助我帮助我将图像(即第一行)的中心放在中心位置,那就太棒了!

代码

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
    }

2 个答案:

答案 0 :(得分:1)

你只需要将你的lebel文本对齐到中心,它就会起作用:

 label.textAlignment = .center

enter image description here

答案 1 :(得分:0)

这是在中心实现欲望图像的代码。

    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

输出

注意:功能没有变化

enter image description here