2016-10-17 15 views
1

我寫了這段代碼,效果很好;但我需要弄清楚CATextLayer中文本的大小才能完成它?我使用輕敲手勢獲取x/y的想法,輸入文本,並找出需要將它繪製在CATextLayer對象/視圖中的CGSize。找出CATextLayer中文本框的大小

overload func ViewDidLoad() 
    let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap)) 
    container.addGestureRecognizer(tap) 
} 

func handleTap(gesture: UITapGestureRecognizer) { 
    let location = gesture.location(in: gesture.view) 
    startX = location.x 
    startY = location.y 
    drawText(onLayer: view.layer, fromPoint: CGPoint(x: startX, y: startY), toPoint: CGPoint(x:location.x, y:location.y)) 
} 

func drawText(onLayer layer: CALayer, fromPoint start: CGPoint, toPoint end:CGPoint) { 
    let myTextLayer = CATextLayer() 
    myTextLayer.string = "Google" 
    myTextLayer.backgroundColor = UIColor.black.cgColor 
    myTextLayer.foregroundColor = UIColor.white.cgColor 
    //myTextLayer.frame = view.bounds 
    let myBounds = CGRect(origin: start, size: CGSize(width: 128, height: 32)) 
    myTextLayer.frame = myBounds 
    layer.addSublayer(myTextLayer) 
} 
+0

這可能有助於http://stackoverflow.com/questions/6198084/resize-catextlayer-to-fit-text-on-ios –

回答

4

是的,Yahoo!

這就是答案!

myTextLayer.preferredFrameSize()