Skip to content

Commit

Permalink
Attempts to fix crash in setMarkedText(_:selectedRange:) (#149)
Browse files Browse the repository at this point in the history
* Extracts string length to variable

* Uses safe selected range
  • Loading branch information
simonbs authored Aug 25, 2022
1 parent ac54109 commit ecd7a27
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions Sources/Runestone/TextView/TextInput/TextInputView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1184,8 +1184,9 @@ extension TextInputView {
}

private func safeSelectionRange(from range: NSRange) -> NSRange {
let cappedLocation = min(max(range.location, 0), stringView.string.length)
let cappedLength = min(max(range.length, 0), stringView.string.length - cappedLocation)
let stringLength = stringView.string.length
let cappedLocation = min(max(range.location, 0), stringLength)
let cappedLength = min(max(range.length, 0), stringLength - cappedLocation)
return NSRange(location: cappedLocation, length: cappedLength)
}

Expand Down Expand Up @@ -1295,7 +1296,8 @@ extension TextInputView {
markedRange = markedText.isEmpty ? nil : NSRange(location: range.location, length: markedText.utf16.count)
replaceText(in: range, with: markedText)
// The selected range passed to setMarkedText(_:selectedRange:) is local to the marked range.
_selectedRange = NSRange(location: range.location + selectedRange.location, length: selectedRange.length)
let preferredSelectedRange = NSRange(location: range.location + selectedRange.location, length: selectedRange.length)
_selectedRange = safeSelectionRange(from: preferredSelectedRange)
delegate?.textInputViewDidUpdateMarkedRange(self)
}

Expand Down

0 comments on commit ecd7a27

Please sign in to comment.