禁用iOS键盘中的空格键

时间:2015-05-19 09:20:36

标签: ios uikeyboard

在我的应用中,我有一个文本字段,可以接受有限数量的字符,因此如果/当他们按空格键时,不希望用户能够在字符之间添加空格。相反,我希望空格键无响应或执行其他功能,如大写而不是添加空格。

有办法做到这一点吗?

3 个答案:

答案 0 :(得分:6)

在Swift中

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if string == " " {
        return false
    } else {
        return true
    }
}

答案 1 :(得分:3)

使用UITextField的下面委托方法并禁止使用空格键。这是在Objective-C。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ( [string isEqualToString:@" "] ){
        return NO;
    }
    else {
        return YES;
    }
}

答案 2 :(得分:2)

请使用下面的代码来识别空格键。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ( [string isEqualToString:@" "] && range.length==0)
    {
        return NO;
    }
    else 
    {
        return YES;
    }
}