igu*_*222 10 iphone cocoa-touch
默认情况下,如果您在iPhone或iPad上点击空格键两次,而不是获得""(两个空格),则会得到"."(一段时间后跟一个空格).有没有办法在代码中禁用此快捷方式?
更新:通过UITextInputTraits禁用自动更正不起作用.
更新2:明白了!请参阅下面的帖子.
sim*_*eon 12
我有一个基于Chaise给出的答案.
Chaise的方法不允许您按顺序键入两个空格 - 在某些情况下这是不可取的.这是一种完全关闭自动周期插入的方法:
在委托方法中:
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
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以根据需要尽可能快地点击空格键,只插入空格.
在委托方法中:
- (BOOL) textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
Run Code Online (Sandbox Code Playgroud)
添加以下代码:
//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;
}
Run Code Online (Sandbox Code Playgroud)
这是我可以在 Swift 4 中解决这个问题的最简单的解决方案。它比其他一些答案更完整,因为它允许连续输入多个空格。
func disableAutoPeriodOnDoubleTapSpace() {
textField.addTarget(self, action: #selector(replaceAutoPeriod), for: .editingChanged)
}
@objc private func replaceAutoPeriod() {
textField.text = textField.text.replacingOccurrences(of: ". ", with: " ")
}
Run Code Online (Sandbox Code Playgroud)
如果您的文本字段的格式为 .attributedText,则您需要在设置 .text 值之前存储旧的 .selectedTextRange 并重置它。否则,在字符串中间进行编辑时,光标将移动到文本的末尾。
希望这可以帮助那些尝试了所有其他答案但没有运气的人!
igu*_*222 -4
好吧,我明白了。在您的 UITextView 委托中,添加以下内容:
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if([text isEqualToString:@". "])
return NO;
}
Run Code Online (Sandbox Code Playgroud)