gpt4 book ai didi

ios - 如何在属性字符串中居中图像?

转载 作者:行者123 更新时间:2023-11-29 11:44:04 25 4
gpt4 key购买 nike

我有一个 image,我想将它与一堆文本一起居中,但即使我将 NSMutableParagraphStyle alignment 设置为 居中,图片所在的线不居中

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
}

最佳答案

你只需要将你的 lebel 文本对齐到中心就可以了:

 label.textAlignment = .center

enter image description here

关于ios - 如何在属性字符串中居中图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44963367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com