Add text to CALayer

前端 未结 7 2008
Happy的楠姐
Happy的楠姐 2020-11-29 19:28

Is it possible to add a UILabel to a CALayer without subclassing and drawing it in drawInContext:?

Thanks!

7条回答
  •  盖世英雄少女心
    2020-11-29 19:53

    Just to document my approach, I did it like this in Swift 4+ :

    let textlayer = CATextLayer()
    
    textlayer.frame = CGRect(x: 20, y: 20, width: 200, height: 18)
    textlayer.fontSize = 12
    textlayer.alignmentMode = .center
    textlayer.string = stringValue
    textlayer.isWrapped = true
    textlayer.truncationMode = .end
    textlayer.backgroundColor = UIColor.white.cgColor
    textlayer.foregroundColor = UIColor.black.cgColor
    
    caLayer.addSublayer(textlayer) // caLayer is and instance of parent CALayer 
    

提交回复
热议问题