From 06690a38be4520d20ce6583ea892552010fbd8bd Mon Sep 17 00:00:00 2001 From: Matt <85322+mattmassicotte@users.noreply.github.com> Date: Fri, 13 Dec 2024 12:19:23 -0500 Subject: [PATCH] move to lineFragment+offset API --- README.md | 2 +- Sources/Glyph/NSTextContainer+Additions.swift | 22 ++++++++----------- 2 files changed, 10 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 281aa38..68e6582 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ func characterIndexes(within rect: CGRect) -> IndexSet func enumerateLineFragments(for rect: CGRect, strictIntersection: Bool, block: (CGRect, NSRange, inout Bool) -> Void) func enumerateLineFragments(in range: NSRange, block: (CGRect, NSRange, inout Bool) -> Void) func enumerateLineFragments(from index: Int, forward: Bool = true, block: (CGRect, NSRange, inout Bool) -> Void) -func lineFragment(after index: Int, forward: Bool = true) -> (CGRect, NSRange)? +func lineFragment(for index: Int, offset: Int) -> (CGRect, NSRange)? func boundingRect(for range: NSRange) -> CGRect? ``` diff --git a/Sources/Glyph/NSTextContainer+Additions.swift b/Sources/Glyph/NSTextContainer+Additions.swift index baddab8..7a1b416 100644 --- a/Sources/Glyph/NSTextContainer+Additions.swift +++ b/Sources/Glyph/NSTextContainer+Additions.swift @@ -81,27 +81,23 @@ extension NSTextContainer { tk1EnumerateLineFragments(from: index, forward: forward, block: block) } - /// Find line fragment details immediately above or below a character index. - public func lineFragment(after index: Int, forward: Bool = true) -> (CGRect, NSRange)? { - var pairs: [(CGRect, NSRange)] = [] + /// Find line fragment offset from the first fragment containing index. + public func lineFragment(for index: Int, offset: Int) -> (CGRect, NSRange)? { + var fragment: (CGRect, NSRange)? + let forward = offset >= 0 + var targetCount = abs(offset) enumerateLineFragments(from: index, forward: forward) { rect, range, stop in - if pairs.count == 2 { + if targetCount == 0 { + fragment = (rect, range) stop = true return } - pairs.append((rect, range)) + targetCount -= 1 } - guard - pairs.count == 2, - let lastLine = pairs.last - else { - return nil - } - - return lastLine + return fragment } }