" [NSBigMutableString substringWithRange:]:范围{0,10}越界;字符串长度9“撤消错误 [英] "[NSBigMutableString substringWithRange:]: Range {0, 10} out of bounds; string length 9" error with Undo
问题描述
当我尝试在 UISearchBar
上执行撤消操作时,我的应用崩溃了。在我的应用程序中,我有代码阻止在搜索栏上输入'%'符号,为此,它将textDidChange方法中的%替换为@,如下所示:
My app crashes when I try to do undo on UISearchBar
. In my app I have code to prevent entering a '%' sign on the search bar and for doing this it replaces a % to @"" in textDidChange method as below:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
self.searchBar.text = [searchText stringByReplacingOccurrencesOfString:@"%" withString:@""];
}
因此,如果我输入文本abc%xyz,则可以看到最终文本搜索栏将是'abcxyz'。不,当我点击撤消时,我看到'xyz'被清除了,我仍然在搜索栏上看到'abc',而不是一次性清除'abcxyz'。
So if I type text "abc%xyz", the final text visible on search bar would be 'abcxyz'. No when I click undo, I see 'xyz' gets cleared and I still see 'abc' on the search bar instead of clearing 'abcxyz' all at one go.
现在,如果我再次点击撤消清除'abc'我的应用程序崩溃 [NSBigMutableString substringWithRange:]:范围超出范围
错误。
Now if I click undo again to clear 'abc' my app crashes with [NSBigMutableString substringWithRange:]: Range out of bounds
error.
我假设即使'%'被@替换,撤销管理器仍可能持有它,因此范围越界。
I am assuming that even though '%' gets replaced by @"", the undo manager might still be holding it and hence the range is going out of bounds.
我在 textDidChange
[searchBar.undoManager removeAllActions]; >我用@替换%,但它没有帮助。以下是代码:
I tried [searchBar.undoManager removeAllActions];
in textDidChange
after I replace % with @"", but it didn't help. Here is the code:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
self.searchBar.text = [searchText stringByReplacingOccurrencesOfString:@"%" withString:@""];
[searchBar.undoManager removeAllActions];
}
问题: 以前有人遇到类似问题吗?如何处理撤消?
Question: Anybody faced similar issue before? How do I handle the undo?
推荐答案
您应该使用此委托方法:
You should be using this delegate method instead:
- (BOOL)searchBar:(UISearchBar *)searchBar
shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text
如果replacementText等于%,则返回NO。这将阻止用户首先使用它,因为它不会更新文本字段,这应该可以解决您遇到的撤消问题。
And just return NO in case the replacementText is equal to "%". This will prevent the user from using it in the first place as it won't update the textfield, which should fix the undo issue you're having.
解决方案
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if([text isEqualToString:@"%"]) {
return NO;
}
return YES;
}
这篇关于" [NSBigMutableString substringWithRange:]:范围{0,10}越界;字符串长度9“撤消错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!