ios - 如何在 Swift 中使用 CoreText 替换 UILabel?

标签 ios swift core-text

目前我正在使用 UILabel 在屏幕上放置文本:

var label = UILabel()
view.addSubView(label)
label.backgroundColor = UIColor.whiteColor()
label.numberOfLines = 2
label.font = UIFont.systemFontOfSize(20, weight: UIFontWeightMedium)
label.frame = CGRectMake(0, 0, 100, 50)
label.text = "Hi, this is some text..."

Swift中如何用CoreText替换上面的?

最佳答案

下面的代码解决了我的问题:

override func drawRect(rect: CGRect) {
    super.drawRect(rect)

    let  context  = UIGraphicsGetCurrentContext()

    // Flip the coordinate system
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    let path = CGPathCreateMutable()
    CGPathAddRect(path, nil, self.bounds)

    let str = NSMutableAttributedString(string: "some text goes here...")

    // set font color
    str.addAttribute(kCTForegroundColorAttributeName as String, value:UIColor.blackColor() , range: NSMakeRange(0,str.length))
    // set font name & size
    let fontRef = UIFont.systemFontOfSize(20, weight: UIFontWeightMedium)
    str.addAttribute(kCTFontAttributeName as String, value: fontRef, range:NSMakeRange(0, str.length))

    let frameSetter = CTFramesetterCreateWithAttributedString(str)
    let ctFrame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0,str.length), path, nil)

    CTFrameDraw(ctFrame, context!)
}

关于ios - 如何在 Swift 中使用 CoreText 替换 UILabel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35335068/

相关文章:

iphone - iOS 每天在特定时间触发本地通知

iphone - ZoomingPDFViewer无法在启用分页的UIScrollViewer中缩放

iphone - NSRange 的多个 CTLine

iPhone:将文本分成框架的行

ios - 核心数据按月和总和分组

ios - iTunes Store 操作失败,缺少所需的图标文件

ios - 如何通过按下按钮从数组中随机快速打印一个简单的引号?

ios - 在 UIPageViewController 中检查后退/前进滚动时的错误

ios - 为什么在使用 titleEdgeInsets 时我的 UIButton 的标题在中间被截断?

iOS:在 UIView 上以 LineWidth 1px 绘制文本