Skip to content

Instantly share code, notes, and snippets.

@krzyzanowskim
Last active January 23, 2022 20:16
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/1835ca54699a0bd79e28414788380367 to your computer and use it in GitHub Desktop.
Save krzyzanowskim/1835ca54699a0bd79e28414788380367 to your computer and use it in GitHub Desktop.
FB9856587

Given a NSTextContentStorage with a single character \n (newline), a layout manager results in 2 line fragments.

Two things to discuss here:

  1. The range of a second TextLineFragment is {1, 0}, that is 0 length range, yet the textLineFragment.attributedString.string value is "\n"
  2. Why two lines at all? I expected a single line. this seems to be a case only if \n is at the end of the storage string. The string "\n\n\n" results in 3 fragments, and 4 lines.
import Cocoa
let layoutManager = NSTextLayoutManager()
layoutManager.textContainer = NSTextContainer(containerSize: NSSize(width: 800, height: 500))
let textStorage = NSTextContentStorage()
textStorage.attributedString = NSAttributedString(string: "\n")
textStorage.addTextLayoutManager(layoutManager)
layoutManager.enumerateTextLayoutFragments(from: nil, options: .ensuresLayout, using: { fragment in
print("line fragments: \(fragment.textLineFragments.count)")
for (idx, textLineFragment) in fragment.textLineFragments.enumerated() {
print("\(idx + 1). \(textLineFragment.characterRange) string: \(textLineFragment.attributedString.string.map(\.unicodeScalars))")
}
return true
})
// line fragments: 2
// 1. {0, 1} string: [StringUnicodeScalarView("\n")]
// 2. {1, 0} string: [StringUnicodeScalarView("\n")]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment