diff --git a/YYText/YYTextView.m b/YYText/YYTextView.m index 01b1629a..2f3f508b 100644 --- a/YYText/YYTextView.m +++ b/YYText/YYTextView.m @@ -1466,11 +1466,13 @@ - (void)_replaceRange:(YYTextRange *)range withText:(NSString *)text notifyToDel if (notify) [_inputDelegate selectionDidChange:self]; } } - if (notify) [_inputDelegate textWillChange:self]; - NSRange newRange = NSMakeRange(range.asRange.location, text.length); - [_innerText replaceCharactersInRange:range.asRange withString:text]; - [_innerText yy_removeDiscontinuousAttributesInRange:newRange]; - if (notify) [_inputDelegate textDidChange:self]; + if (range.asRange.location+range.asRange.length <= _innerText.length) { + if (notify) [_inputDelegate textWillChange:self]; + NSRange newRange = NSMakeRange(range.asRange.location, text.length); + [_innerText replaceCharactersInRange:range.asRange withString:text]; + [_innerText yy_removeDiscontinuousAttributesInRange:newRange]; + if (notify) [_inputDelegate textDidChange:self]; + } } /// Save current typing attributes to the attributes holder. @@ -3344,11 +3346,15 @@ - (void)setMarkedText:(NSString *)markedText selectedRange:(NSRange)selectedRang if (!markedText) markedText = @""; if (_markedTextRange == nil) { _markedTextRange = [YYTextRange rangeWithRange:NSMakeRange(_selectedTextRange.end.offset, markedText.length)]; - [_innerText replaceCharactersInRange:NSMakeRange(_selectedTextRange.end.offset, 0) withString:markedText]; + if (_selectedTextRange.end.offset<=_innerText.length) { + [_innerText replaceCharactersInRange:NSMakeRange(_selectedTextRange.end.offset, 0) withString:markedText]; + } _selectedTextRange = [YYTextRange rangeWithRange:NSMakeRange(_selectedTextRange.start.offset + selectedRange.location, selectedRange.length)]; } else { _markedTextRange = [self _correctedTextRange:_markedTextRange]; - [_innerText replaceCharactersInRange:_markedTextRange.asRange withString:markedText]; + if (_markedTextRange.asRange.location+_markedTextRange.asRange.length<=_innerText.length) { + [_innerText replaceCharactersInRange:_markedTextRange.asRange withString:markedText]; + } _markedTextRange = [YYTextRange rangeWithRange:NSMakeRange(_markedTextRange.start.offset, markedText.length)]; _selectedTextRange = [YYTextRange rangeWithRange:NSMakeRange(_markedTextRange.start.offset + selectedRange.location, selectedRange.length)]; }