Skip to content

Instantly share code, notes, and snippets.

@krzyzanowskim
Last active October 28, 2023 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krzyzanowskim/1d45252f98a6f76bdd3aa320de7456f6 to your computer and use it in GitHub Desktop.
Save krzyzanowskim/1d45252f98a6f76bdd3aa320de7456f6 to your computer and use it in GitHub Desktop.
"given this many pixels and a string with these attributes, tell me the optimal places to do a line break" https://iosdevelopers.slack.com/archives/C1GPPBMHC/p1697470218613869?thread_ts=1697467894.270959&cid=C1GPPBMHC
import Cocoa
/// "given this many pixels and a string with these attributes, tell me the optimal places to do a line break"
class LineBreakPropose: NSObject, NSTextLayoutManagerDelegate {
var lineBreaks: [NSTextLocation] = []
init(_ attributedString: NSAttributedString, in size: CGSize, by lineBreakMode: NSLineBreakMode = .byWordWrapping) {
super.init()
let textContentManager = NSTextContentStorage()
// Layout
let textLayoutManager = NSTextLayoutManager()
textLayoutManager.delegate = self
textContentManager.addTextLayoutManager(textLayoutManager)
textContentManager.primaryTextLayoutManager = textLayoutManager
let textContainer = NSTextContainer()
textLayoutManager.textContainer = textContainer
textContainer.lineFragmentPadding = 0
textContainer.lineBreakMode = lineBreakMode
textContainer.size = size
textContentManager.attributedString = attributedString //NSAttributedString(string: "0123456789 0123456789 012")
textLayoutManager.ensureLayout(for: textContentManager.documentRange)
}
func textLayoutManager(_ textLayoutManager: NSTextLayoutManager, shouldBreakLineBefore location: NSTextLocation, hyphenating: Bool) -> Bool {
lineBreaks.append(location)
return true
}
}
let breakLocations = LineBreakPropose(NSAttributedString(string: "0123456789 0123456789 012"), in: CGSize(width: 40, height: 10000)).lineBreaks
print(breakLocations)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment