swiftcatextlayer

How to get "string" attribute value of CATextLayer in swift 4?


I am trying to access the text value in the CATextlayer, I can access other values but this string attribute cannot be accessed and it isn't even displayed on intellisence either. Is there some other way to access it ? I am new to swift.I have something like below:

let textLayer = CATextLayer()
textLayer.isHidden = true
textLayer.contentsScale = UIScreen.main.scale
textLayer.fontSize = 14
textLayer.font = UIFont(name: "textLayer = CATextLayer()
textLayer.isHidden = true
textLayer.contentsScale = UIScreen.main.scale
textLayer.fontSize = 14
textLayer.font = UIFont(name: "Avenir", size: textLayer.fontSize)
textLayer.alignmentMode = kCAAlignmentCenter", size:textLayer.fontSize)
textLayer.string = "someText"
textLayer.foregroundColor = textColor.cgColor
textLayer.backgroundColor = color.cgColor
textLayer.isHidden = false
textLayer.contentsScale = UIScreen.main.scale
textLayer.name="someText"

and I want to access this string attribute value like

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first

    guard let point = touch?.location(in: cameraView) else { return }

    print(self.selectedObject = cameraView.layer.sublayers![2].string!)

    self.selectedObject = cameraView.layer.sublayers![2].name!//Textlayer
  // print(cameraView.layer.sublayers![3])//shapelayer


}

Solution

  • The sublayers property is declared as the base class [CALayer]

    To get a value from a particular CALayer subclass you have to cast the type

    if let textLayer = cameraView.layer.sublayers?[2] as? CATextLayer {
        print(textLayer.string!)
    }