我有一个 UITextView,我在其中插入逗号分隔值。但是当我插入任何文本并在其后给出两个或更多空格时。它会自动在最后一个文本后添加句号。
是因为手机设置的原因吗?即使是。我们该如何预防呢?
编辑要重现它..在 UITextView 中输入任何单词,然后尝试应用两个空格。它会自动在单词末尾添加句号:)
这是因为设定'。'键盘设置中的快捷键。
Apple 将该行为描述为:“双击空格键将插入一个句点,后跟一个空格”,这确实是一个 iOS 系统设置(“设置/常规/键盘/”。“快捷方式)。
用户可以禁用该行为,但通过特定 UITextView 上的代码禁用它似乎很困难 - 请参阅 iPhone:禁用“双击空格键”。捷径?
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
//Check for double space
return !(range.location > 0 &&
[text length] > 0 &&
[[NSCharacterSet whitespaceCharacterSet] characterIsMember:[text characterAtIndex:0]] &&
[[NSCharacterSet whitespaceCharacterSet] characterIsMember:[[textView text] characterAtIndex:range.location - 1]]);
}
以上代码将限制用户输入多个空格。
你需要检查前一个和替换的字符是否都是空的,并自己替换而不是iOS才有机会获得第二个空的空间。
从处理程序返回 false 可以实现这一点:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
{
guard let textViewText = textView.text, range.location > 0 else {
return true
}
let previousCharIndex = textViewText.index(textViewText.startIndex, offsetBy: range.location - 1)
let previousChar = textViewText[previousCharIndex]
if previousChar == " " && text == " " {
let insertionPoint = textViewText.index(textViewText.startIndex, offsetBy: range.location)
textView.text?.insert(" ", at: insertionPoint)
return false
}
return true
}