【发布时间】:2015-12-31 15:04:07
【问题描述】:
我正在尝试删除 uitextview 中突出显示的文本。例如,如果我有文字
“我要回家了”
如果我想删除“去”这个词
我收到此错误
'NSRangeException',原因:'-[__NSCFString substringWithRange:]: 范围 {15, 0} 越界;字符串长度 13'
编辑:
此行发生错误
[textViewText replaceCharactersInRange:range withAttributedString:formatString]
这里是变量值
range = {4,1} //{_rangestart, _rangeEnd}
formatString= " "
textViewText="I am home" //extra space there
{
NSMutableAttributedString *formatString;
if(_rangeEnd == 0)
{
_rangeStart -=1;
_rangeEnd = 1;
}
else if(_rangeEnd > 1)
{
// _rangeStart -=1;
}
else
{
_rangeStart +=1;
}
NSRange range = NSMakeRange(_rangeStart, _rangeEnd);
NSDictionary *attrDict = @{
NSFontAttributeName : _boldFont,
NSFontAttributeName : _italicFont,
NSForegroundColorAttributeName : _color,
NSBackgroundColorAttributeName: _backgroundColor,
};
NSMutableAttributedString *textViewText = [[NSMutableAttributedString alloc]initWithAttributedString:textView.attributedText];
formatString = [[NSMutableAttributedString alloc]initWithString:_selectedText attributes:attrDict];
if(_underline == YES)
{
[formatString addAttribute:NSUnderlineStyleAttributeName
value:[NSNumber numberWithInt:1]
range:(NSRange){0,[formatString length]}];
}
if(_strikeThrough == YES)
{
[formatString addAttribute:NSStrikethroughStyleAttributeName
value:[NSNumber numberWithInt:1]
range:(NSRange){0,[formatString length]}];
}
NSNumber *location = [NSNumber numberWithInteger:range.location];
if(location < 0 || location == nil)
{
range.location=0;
}
if(textViewText.length > 0 && formatString.length > 0)
{
[textViewText replaceCharactersInRange:range withAttributedString:formatString];
dispatch_async(dispatch_get_main_queue(), ^{
textView.attributedText = textViewText;
[textView setTextAlignment:_alignment];
});
}
这是调用上述函数的委托
- (void)textViewDidChange:(UITextView *)textView{
_textV = textView;
_selectedText = [textView.text substringWithRange:textView.selectedRange];
_rangeStart = textView.selectedRange.location;
_rangeEnd = textView.selectedRange.length;
if([_selectedText isEqual:@""] && _rangeEnd == 0)
{
_selectedText = [textView.text substringWithRange:NSMakeRange(_rangeStart - 1, 1)];
[self applyBold:textView];
}
NSDictionary *event = @{
@"target": textView.reactTag,
@"highlights": @{
@"text": textView.text,
@"range": @(textView.selectedRange.length),
@"cursorPosition": @(textView.selectedRange.location),
@"eventType": @"textViewDidChange",
}
};
[self.bridge.eventDispatcher sendInputEventWithName:@"topChange" body:event];
}
【问题讨论】:
-
错误发生在哪里确切?
-
在不知道
_rangeStart和_rangeEnd的设置以及设置的值的情况下,谁能帮助您? -
你知道
NSMakeRange的参数是开始和长度,而不是开始和结束,对吧? -
你应该把它命名为长度,然后,它对每个人都更有意义,包括你。
-
能否提供
textView、range的实际值以及匹配在一起的错误信息?确保这些是调用replaceCharactersInRange:withAttributedString:时的实际值,而不是您认为的值,因为您在之前的某个时间点在难以理解的逻辑中记录了它们。
标签: objective-c uitextview react-native indexoutofboundsexception outofrangeexception