【发布时间】:2015-01-14 11:29:53
【问题描述】:
我有一个 UITextField,用户需要在其中输入电话号码。
这就是现在的样子:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// Auto-add hyphen before appending 4rd or 7th digit
//
//
if (range.length == 0 && (range.location == 3 || range.location == 7))
{
textField.text = [NSString stringWithFormat:@"%@-%@", textField.text, string];
return NO;
}
// Delete hyphen when deleting its trailing digit
//
//
if (range.length == 1 && (range.location == 4 || range.location == 8))
{
range.location--;
range.length = 2;
textField.text = [textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
// Prevent crashing undo bug – see note below.
//
//
if (range.length + range.location > textField.text.length)
{
return NO;
}
// Limit text field characters
//
//
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 12) ? NO : YES;
}
在第 3 位数字之后,我添加了一个连字符,然后又添加了一个连字符。我在这里想要实现的是在UITextField 的开头添加一个国家代码作为常量,并且用户将无法删除它。假设是美国国家代码,那么 UITextField 文本将在开头 +1- 时看起来像这样,然后在写完完整数字后,它将看起来像这样:+1-600-242-252
我该怎么做?
提前致谢!
【问题讨论】:
标签: ios objective-c iphone uitextfield