问题
I have an UITextView which is for instance 380 characters in length:
NSLog(@"aTextView.text lenght %i", aTextView.text.length);
I now want to go through this text (backwards, char by char) and delete all characters which come before the last space (e.g. if the last words were "...this is an example", it want to reduce the string to "...this is an ":
for (int i = aTextView.text.length-1; i > 0; i--) {
NSString *checkedChar = [NSString stringWithFormat:@"%c", [aTextView.text characterAtIndex:i]];
NSLog(@"I currently check: %@", checkedChar);
if ([checkedChar isEqualToString:@" "]) {
// job done
i = 0; // this ends the loop
} else {
I need something like [aTextView.text removeCharacterAtIndex:i];
}
}
How do I achieve this? I couldn't find any methods in the docs and would be very grateful for suggestions.
EDIT:
NSString *myString = aTextView.text;
NSRange range = [myString rangeOfString:@" " options:NSBackwardsSearch];
NSString *oldText = [myString subStringToIndex:range.location];
NSString *newText = [myString subStringFromIndex:range.location];
NSLog(@"++++ OLD TEXT ++++: %@", oldText);
NSLog(@"++++ NEW TEXT ++++: %@", newText);
aTextView.text = oldText;
This crashes my app... I am calling this from - (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString *)aText
I get the error message: * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString subStringToIndex:]: unrecognized selector sent to instance 0x4e33850'
And xCode gives me the warning the subStringToIndex may not respond...
回答1:
You don't need a loop to do this - take a look at NSString' rangeOfString:options: and substringToIndex: methods. For example :
NSRange range = [myString rangeOfString:@" " options:NSBackwardsSearch];
NSString *newString = [myString substringToIndex:range.location];
Hope that helps.
NB Don't forget to check that your string definitely contains a space ;)
回答2:
This is very easy in iOS 5 or later:
// This is your delete button method.
-(IBAction)btnDelete:(id)sender
{
// txtView is UITextView
if([txtView.text length] > 0)
{
[txtView deleteBackward];
}
}
来源:https://stackoverflow.com/questions/6072556/how-to-delete-single-characters-in-an-uitextview