My macOS app generates PDF files using fixed size CATextLayers. Each text layer has text of different lengths and need to be word wrapped when the length of the text line exceeds the bounds of the frame. However, if the lines of text exceed the height of the bounding frame, the font size will need to be reduced by one and then rechecked to ensure the text is contained within the bounding box. I'm assuming the wrapping would be automatic if the font size is reduced, i.e. re-wrapped?
But, it seems everything I read is for UIKit and using UIFont, which doesn't work in macOS.
It appears boundingRectWithSize:options:attributes:context:
might be what I need to use to get the size from my text string and then keep reducing the font size until the returned height and width are within the max size of the fixed size of my CATextLayer. Unfortunately, again, the examples I find are either for iOS or written in Objective-C.
This is what I've been toying around with, but I'm getting a crash "Bad Execution" error. Also, I do not know how to set the nsString font size or word wrapping attributes. Am I approaching this totally wrong?
import Cocoa
let myTextLayer = CATextLayer()
let rectWidth = 70
let rectHeight = 70
var fontSize = 14
var tempBox = CGSize(width: 71, height: 71)
let str = "This string has some really, really, really long text"
func sizeOfString(nsString: NSString) -> CGSize {
return nsString.boundingRect(
with: CGSize(width: CGFloat.infinity, height:CGFloat.infinity),
options: NSString.DrawingOptions.usesLineFragmentOrigin,
attributes: [NSAttributedString.Key.font: "Helvetica"],
context: nil).size
}
while sizeOfString(nsString: str as NSString).width > tempBox.width || sizeOfString(nsString: str as NSString).height > tempBox.height {
fontSize -= 1
}
myTextLayer.string = str
myTextLayer.fontSize = CGFloat(fontSize)
myTextLayer.alignmentMode = .center
print(tempBox)
print(fontSize)
Appreciate any help or leading me into a direction where I can work out a solution.