禁用UITextField键盘快捷方式建议。

26

有没有一种简单的方法可以从 UITextField 中删除 键盘快捷方式建议

可以使用以下代码删除输入更正: [textField setAutocorrectionType:UITextAutocorrectionTypeNo]; 然而这对于快捷方式没有影响。

影响共享菜单控制器也不能解决这个问题。

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    [UIMenuController sharedMenuController].menuVisible = NO;
    return  NO;
}

这里输入图片的描述

9个回答

46

4

仅在必要时使用此功能

  textField.autocorrectionType = UITextAutocorrectionTypeNo;

4
通过实现UITextFieldDelegate方法并手动设置UITextField的文本属性来解决此问题。在模拟器中,默认情况下可以通过输入“omw”来测试此行为,这应该会建议“On my way! ”。以下代码将阻止此操作。请注意:这也会禁用自动更正和检查拼写,但在我的情况下没关系。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // Pass through backspace and character input
    if (range.length > 0 && [string isEqualToString:@""]) {
        textField.text = [textField.text substringToIndex:textField.text.length-1];
    } else {
        textField.text = [textField.text stringByAppendingString:string];
    }
    // Return NO to override default UITextField behaviors
    return NO;
}

很好!有没有新的默认解决方案? - Hassan Taleb

1

Matt的解决方案转换为Swift 5:

func textField(_ textField: UITextField,
               shouldChangeCharactersIn range: NSRange,
               replacementString string: String) -> Bool {
    // Pass through backspace and character input
    if (range.length > 0 && string.isEmpty) {
        textField.text?.removeLast()
    } else {
        textField.text?.append(string)
    }
    // Return false to override default UITextField behaviors
    return false
}

0

上述答案可能无法处理剪切/复制/粘贴的情况。例如,在UITextField中剪切和粘贴文本时,结果不符合默认功能。

以下是类似的方法:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

NSString *textFieldNewText = [textField.text stringByReplacingCharactersInRange:range withString:string];

    if ([string isEqualToString:@""]) {
        // return when something is being cut
        return YES;
    }
    else
    {
        //set text field text
        textField.text=textFieldNewText;
        range.location=range.location+[string length];
        range.length=0;
        [self selectTextInTextField:textField range:range];
    }
    return NO;
}


//for handling cursor position when setting textfield text through code
- (void)selectTextInTextField:(UITextField *)textField range:(NSRange)range {

    UITextPosition *from = [textField positionFromPosition:[textField beginningOfDocument] offset:range.location];
    UITextPosition *to = [textField positionFromPosition:from offset:range.length];
    [textField setSelectedTextRange:[textField textRangeFromPosition:from toPosition:to]];
}

0

使用 AutocorrectionType:

[mailTextField setAutocorrectionType:UITextAutocorrectionTypeNo];


0

Swift 3.x或以上版本:

textField.autocorrectionType = .no

0
textField.autocorrectionType = .No

0
UITextField* f = [[UITextField alloc] init];
f.autocorrectionType = UITextAutocorrectionTypeNo;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接