У меня есть ответ, основанный на ответе, приведенном Шезе выше.
Метод Чейза не позволяет вам вводить два пробела в последовательности - это нежелательно в некоторых ситуациях. Вот способ полностью отключить автоматическую вставку:
Swift
В методе делегата:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
//Ensure we're not at the start of the text field and we are inserting text
if range.location > 0 && text.count > 0
{
let whitespace = CharacterSet.whitespaces
let start = text.unicodeScalars.startIndex
let location = textView.text.unicodeScalars.index(textView.text.unicodeScalars.startIndex, offsetBy: range.location - 1)
//Check if a space follows a space
if whitespace.contains(text.unicodeScalars[start]) && whitespace.contains(textView.text.unicodeScalars[location])
{
//Manually replace the space with your own space, programmatically
textView.text = (textView.text as NSString).replacingCharacters(in: range, with: " ")
//Make sure you update the text caret to reflect the programmatic change to the text view
textView.selectedRange = NSMakeRange(range.location + 1, 0)
//Tell UIKit not to insert its space, because you've just inserted your own
return false
}
}
return true
}
Теперь вы можете нажимать пробел столько раз, сколько хотите, вставляя только пробелы.
Objective-C
В методе делегата:
- (BOOL) textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
Добавьте следующий код:
//Check if a space follows a space
if ( (range.location > 0 && [text length] > 0 &&
[[NSCharacterSet whitespaceCharacterSet] characterIsMember:[text characterAtIndex:0]] &&
[[NSCharacterSet whitespaceCharacterSet] characterIsMember:[[textView text] characterAtIndex:range.location - 1]]) )
{
//Manually replace the space with your own space, programmatically
textView.text = [textView.text stringByReplacingCharactersInRange:range withString:@" "];
//Make sure you update the text caret to reflect the programmatic change to the text view
textView.selectedRange = NSMakeRange(range.location+1, 0);
//Tell Cocoa not to insert its space, because you've just inserted your own
return NO;
}