Skip to content

Commit ce1257d

Browse files
committed
Add documentation
1 parent 1d2f62a commit ce1257d

File tree

1 file changed

+24
-9
lines changed

1 file changed

+24
-9
lines changed

Sources/CodeEditTextView/TextView/TextView+ScrollToVisible.swift

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

40-
public func scrollToRange(_ range: NSRange) {
40+
41+
/// Scrolls the view to the specified range.
42+
///
43+
/// - Parameters:
44+
/// - range: The range to scroll to.
45+
/// - center: A flag that determines if the range should be centered in the view. Defaults to `true`.
46+
///
47+
/// 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.
48+
public func scrollToRange(_ range: NSRange, center: Bool = true) {
4149
guard let scrollView else { return }
4250

4351
guard let boundingRect = layoutManager.rectForOffset(range.location) else { return }
@@ -47,15 +55,23 @@ extension TextView {
4755
return // No scrolling needed
4856
}
4957

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-
)
58+
// Calculate the target offset based on the center flag
59+
let targetOffset: CGPoint
60+
if center {
61+
targetOffset = CGPoint(
62+
x: max(boundingRect.midX - visibleRect.width / 2, 0),
63+
y: max(boundingRect.midY - visibleRect.height / 2, 0)
64+
)
65+
} else {
66+
targetOffset = CGPoint(
67+
x: max(boundingRect.origin.x, 0),
68+
y: max(boundingRect.origin.y, 0)
69+
)
70+
}
5571

5672
var lastFrame: CGRect = .zero
5773

58-
// Set a timeout to avoid a infinite loop
74+
// Set a timeout to avoid an infinite loop
5975
let timeout: TimeInterval = 0.5
6076
let startTime = Date()
6177

@@ -69,7 +85,7 @@ extension TextView {
6985
selectionManager.drawSelections(in: visibleRect)
7086
}
7187

72-
// Scroll to make the range appear in the middle of the screen
88+
// Scroll to make the range appear at the desired position
7389
if lastFrame != .zero {
7490
let animated = false // feature flag
7591
if animated {
@@ -83,7 +99,6 @@ extension TextView {
8399
}
84100
}
85101
}
86-
87102
/// Get the selection that should be scrolled to visible for the current text selection.
88103
/// - Returns: The the selection to scroll to.
89104
private func getSelection() -> TextSelection? {

0 commit comments

Comments
 (0)