iPhone:禁用 "double-tap spacebar for ."快捷方式?

标签 iphone cocoa-touch

默认情况下,如果您在 iPhone 或 iPad 上点击空格键两次,则不会得到“  ”(两个空格),而是得到“. ”(句点后跟一个空格)。有什么方法可以在代码中禁用此快捷方式吗?

更新:通过 UITextInputTraits 禁用自动更正不起作用。

更新2:明白了!请参阅下面我的帖子。

最佳答案

我有一个基于上面 Chaise 给出的答案。

Chaise 的方法不允许您依次键入两个空格 - 在某些情况下这是不可取的。这是完全关闭自动句点插入的方法:

swift

在委托(delegate)方法中:

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
}

现在您可以按您喜欢的次数和速度点击空格键,仅插入空格。

目标-C

在委托(delegate)方法中:

- (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;
}

关于iPhone:禁用 "double-tap spacebar for ."快捷方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2576561/

相关文章:

iphone - 对 NSMutableArray 进行排序

iphone - 在没有 BluetoothManager 的情况下检查 iOS 5 上的蓝牙是否被禁用

iOS 限制 64 个本地通知

iphone - iOS - 确定选择了哪个 MKPointAnnotation

iphone - 更改 uitabbaritem 的文本颜色

iphone - iPhone Interface Builder 中的自定义控件

iphone - 如何通过代码将UISearchBar设置为黑色半透明?

ios - 防止 initWithContentsOfURL : from using cache

iphone - 在 cocoa 中放置 "constants"的位置

ios - 一起发送多个 OBD 命令并同时获得响应