Search code examples
iosswiftcore-text

How to use CoreText to replace UILabel in Swift?


Currently I am using UILabel to put texts on the screen:

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..."

How to use CoreText to replace the above in Swift?


Solution

  • Following code solved my question:

    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!)
    }