Skip to content

Commit c4f2cb1

Browse files
committed
Add documentation
1 parent 1d2f62a commit c4f2cb1

File tree

1 file changed

+23
-8
lines changed

1 file changed

+23
-8
lines changed

Sources/CodeEditTextView/TextView/TextView+ScrollToVisible.swift

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,14 @@ extension TextView {
3737
}
3838
}
3939

40-
public func scrollToRange(_ range: NSRange) {
40+
/// Scrolls the view to the specified range.
41+
///
42+
/// - Parameters:
43+
/// - range: The range to scroll to.
44+
/// - center: A flag that determines if the range should be centered in the view. Defaults to `true`.
45+
///
46+
/// If `center` is `true`, the range will be centered in the visible area. If `center` is `false`, the range will be aligned at the top-left of the view.
47+
public func scrollToRange(_ range: NSRange, center: Bool = true) {
4148
guard let scrollView else { return }
4249

4350
guard let boundingRect = layoutManager.rectForOffset(range.location) else { return }
@@ -47,15 +54,23 @@ extension TextView {
4754
return // No scrolling needed
4855
}
4956

50-
// Calculate the target offset to center the range in the view
51-
let targetOffset = CGPoint(
52-
x: max(boundingRect.midX - visibleRect.width / 2, 0),
53-
y: max(boundingRect.midY - visibleRect.height / 2, 0)
54-
)
57+
// Calculate the target offset based on the center flag
58+
let targetOffset: CGPoint
59+
if center {
60+
targetOffset = CGPoint(
61+
x: max(boundingRect.midX - visibleRect.width / 2, 0),
62+
y: max(boundingRect.midY - visibleRect.height / 2, 0)
63+
)
64+
} else {
65+
targetOffset = CGPoint(
66+
x: max(boundingRect.origin.x, 0),
67+
y: max(boundingRect.origin.y, 0)
68+
)
69+
}
5570

5671
var lastFrame: CGRect = .zero
5772

58-
// Set a timeout to avoid a infinite loop
73+
// Set a timeout to avoid an infinite loop
5974
let timeout: TimeInterval = 0.5
6075
let startTime = Date()
6176

@@ -69,7 +84,7 @@ extension TextView {
6984
selectionManager.drawSelections(in: visibleRect)
7085
}
7186

72-
// Scroll to make the range appear in the middle of the screen
87+
// Scroll to make the range appear at the desired position
7388
if lastFrame != .zero {
7489
let animated = false // feature flag
7590
if animated {

0 commit comments

Comments
 (0)