ios - 限制删除 UITextField

标签 ios nsstring uitextfield restriction

我有一个 UITextField,其中包含类似 +91- 的文本(这是印度的国家/地区来电代码)。现在,当我的用户将他的号码输入该文本字段时,它看起来像这样,+91-1234567890 很好,现在当他点击键盘上的 (x) 删除键时,我想限制删除,它最多只能到1(他的手机号码的第一位数字),无论如何,他应该无法删除+91-。我可以用 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; 委托(delegate)来做到这一点,就像这样,

1)第一种方式:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if([string isEqualToString:@""]) { //detect back space
        if([textField.text hasSuffix:@"-"]) { //has suffix `-`
            return NO;
        }
    }
}

2)第二种方式:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //if text length is length of caller code and detect back space
    if(textField.text.length<=4 && [string isEqualToString:@""]) {
        return NO;
    }

    return YES;
}

在这两种方式中,我都得到了我想要的,但不确定它是否合适?还有更顺畅的方法吗?

最佳答案

为什么你不像简单的方法那样尝试在 UItextfield 的前缀中再添加一个 UIView

enter image description here

关于ios - 限制删除 UITextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27010271/

相关文章:

ios - 按下按钮时如何显示事件卡

ios - 将多个文本和变量连接成一个字符串 iOS?

ios - remoteControlReceivedWithEvent 中的 Nil 值

ios - 有没有更好的方法来排除 tvOS 的 navigationBarTitle?

iphone - 在 IOS 上使用 AFNetworking 流式传输 JSON

Objective-C Mac OSX 应用程序 - 从另一个委托(delegate)获取变量?

objective-c - 无法从 Cocoa NSMutableString 中去除换行符

ios - (Swift) 将 UIDatePicker 选择的日期分配给 UITextField

ios - 如何禁用特定文本字段上的键盘但允许选择器 View 作为输入 Swift?

ios - textFieldShouldBeginEditing : Only Recognizes 1 textField