【发布时间】:2019-08-07 19:30:16
【问题描述】:
我有一个名为“矩形”的类来制作自定义 UILabel。我覆盖了矩形类中的“绘制”。当我实例化标签时,我希望第一行文本以粗体显示。我知道如何通过手动获取每个字符串的范围来解决这个问题……但是,我有 300 多个字符串要做。字符串当前位于一个数组中,格式如下:“Happy \n Birthday”。我怎样才能使“快乐”这个词变得粗体?
var messageText = "Happy \n Birthday"
let rectanglePath = UIBezierPath(rect: rectangleRect)
context.saveGState()
UIColor.white.setFill()
rectanglePath.fill()
context.restoreGState()
darkPurple.setStroke()
rectanglePath.lineWidth = 0.5
rectanglePath.lineCapStyle = .square
rectanglePath.lineJoinStyle = .round
rectanglePath.stroke()
let rectangleStyle = NSMutableParagraphStyle()
rectangleStyle.alignment = .center
let rectangleFontAttributes = [
.font: UIFont.myCustomFont(true),
.foregroundColor: UIColor.black,
.paragraphStyle: rectangleStyle,
] as [NSAttributedString.Key: Any]
let rectangleTextHeight: CGFloat = messageText.boundingRect(with: CGSize(width: rectangleRect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: rectangleFontAttributes, context: nil).height
context.saveGState()
context.clip(to: rectangleRect)
messageText.draw(in: CGRect(x: rectangleRect.minX, y: rectangleRect.minY + (rectangleRect.height - rectangleTextHeight) / 2, width: rectangleRect.width, height: rectangleTextHeight), withAttributes: rectangleFontAttributes)
context.restoreGState()
【问题讨论】:
-
你为什么不找
\n? -
您能详细说明一下吗?我尝试迭代直到 \n 但它没有编译
标签: ios swift uilabel nsattributedstring nsrange