gpt4 book ai didi

ios - 如何在 Swift 中绘制水平对齐的 NSAttributedString

转载 作者:行者123 更新时间:2023-11-30 12:22:20 25 4
gpt4 key购买 nike

我正在尝试绘制一个多行字符串,使每行与框的中心水平对齐。我正在使用 NSAttributedString,因此:

let paraStyle = NSMutableParagraphStyle()
paraStyle.alignment = .center
textAttrs = [
NSFontAttributeName: font!,
NSForegroundColorAttributeName: UIColor.white,
NSParagraphStyleAttributeName: paraStyle,
NSBaselineOffsetAttributeName: NSNumber(floatLiteral: 0.0)
]

然后我使用 NSAttributedString draw() 绘制字符串

let uiText = NSAttributedString(string: text, attributes: textAttrs)
let point = CGPoint(x: self.bounds.width / 2 - uiText.size().width / 2, y: self.bounds.height / 2 - uiText.size().height / 2)
uiText.draw(at: point)

但它仍然每行都左对齐。如何在ios中绘制字符串并居中对齐。

最佳答案

您可能需要使用draw(in rect: CGRect),而不是draw(at point: CGPoint)

override func draw(_ rect: CGRect) {

let paraStyle = NSMutableParagraphStyle()
paraStyle.alignment = .center

let textAttrs = [
NSFontAttributeName: UIFont.systemFont(ofSize: 17),
NSForegroundColorAttributeName: UIColor.blue,
NSParagraphStyleAttributeName: paraStyle,
NSBaselineOffsetAttributeName: NSNumber(floatLiteral: 0.0)
]

let text = "The American student who was released last week after being held in captivity for more than 15 months in North Korea has died, his family says. Otto Warmbier, 22, returned to the US last Tuesday, but it emerged he had been in a coma for a year.North Korea said botulism led to the coma, but a team of US doctors who assessed him dispute this account.Mr Warmbier was sentenced to 15 years of hard labour for attempting to steal a propaganda sign from a hotel."

let uiText = NSAttributedString(string: text, attributes: textAttrs)
uiText.draw(in: rect)

layer.borderColor = UIColor.black.cgColor
layer.borderWidth = 2
}

smaple

关于ios - 如何在 Swift 中绘制水平对齐的 NSAttributedString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44642373/

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