[英]Adding a constant country code at beginning of UITextField
我有一個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;
}
在第三個數字之后,我要加上連字符,然后再加上。 我在這里想要實現的是在UITextField
開頭添加一個國家/地區代碼作為常量,並且用戶將無法刪除它。 假設是美國國家/地區代碼,則UITextField
文本在開始時為+1-
,然后在寫入完整的數字后將如下所示: +1-600-242-252
我怎樣才能做到這一點?
提前致謝!
該答案假定一個起始的國家代碼字符串,該字符串的末尾包括連字符,例如: self.countryCode = @"+1-";
。 文本字段最初應包含“ + 1-”。
我已經使回答的方式比您的初衷更加全面,因為它可以處理您忽略的許多用例,例如,具有多個字符的復制和粘貼操作,不適當的連字符刪除,不適當的連字符添加,中線插入等。仍然不是很完美,因為您的原始答案在某些方面是不確定的...例如,如果您指定用戶只能輸入數字,則代碼可以更簡潔。
全文中包含的注釋逐行描述了以下實現。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// Combine the new text with the old
NSMutableString *combinedText = [[textField.text stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"%@", string]] mutableCopy];
// If the user deletes part of the country code or tries
// to edit it in any way, don't allow it
if (combinedText.length < self.countryCode.length ||
![combinedText hasPrefix:self.countryCode]) {
return NO;
}
// Limit text field characters to 12
if (combinedText.length > self.countryCode.length + 12) {
return NO;
}
// If the user tries to add a hyphen where there's supposed
// to be a hyphen, allow them to do so.
if ([string isEqualToString:@"-"] &&
(range.location == self.countryCode.length + 3 ||
range.location == self.countryCode.length + 7)) {
return YES;
}
// Remove all the hyphens other than the one directly
// following the country code
[combinedText replaceOccurrencesOfString:@"-" withString:@"" options:0 range:NSMakeRange(self.countryCode.length, [combinedText length] - self.countryCode.length)];
// Auto-add the hyphens before the 4th and 7th digits
if (combinedText.length > self.countryCode.length + 3)
[combinedText insertString:@"-" atIndex:self.countryCode.length + 3];
if (combinedText.length > self.countryCode.length + 7)
[combinedText insertString:@"-" atIndex:self.countryCode.length + 7];
// Store the original cursor position
UITextPosition *pos = [textField selectedTextRange].start;
// Count up the original number of hyphens
NSUInteger originalNumberOfHyphens = [[textField.text componentsSeparatedByString:@"-"] count] - 1;
// Count up the new number of hyphens
NSUInteger newNumberOfHyphens = [[combinedText componentsSeparatedByString:@"-"] count] - 1;
// Create a cursor offset to reflect the difference
// in the number of hyphens
float offset = newNumberOfHyphens - originalNumberOfHyphens;
// Update the text field to contain the combined text
textField.text = combinedText;
// Update the cursor position appropriately
if (string.length > 0) {
UITextPosition* cursor = [textField positionFromPosition:[textField beginningOfDocument] offset:range.location + range.length + offset + string.length];
textField.selectedTextRange = [textField textRangeFromPosition:cursor toPosition:cursor];
} else {
UITextPosition* cursor = [textField positionFromPosition:pos inDirection:UITextLayoutDirectionLeft offset:1-offset];
textField.selectedTextRange = [textField textRangeFromPosition:cursor toPosition:cursor];
}
// No need to replace the string since it's already been done
return NO;
}
為了在開始時保持常量,您基本上想檢查常量是否仍然存在於建議的文本中。 如果它不拒絕這樣的編輯。
您不應嘗試在特定的編輯步驟中插入連字符。 最好操縱整個字符串。
例如
starts with +1
在代碼中,它看起來像這樣:
- (void)viewDidLoad {
[super viewDidLoad];
self.textField.text = @"+1"; // start with a +1 in the textField otherwise we can't change the field at all
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *proposedText = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (![proposedText hasPrefix:@"+1"]) {
// tried to remove the first +1
return NO;
}
NSString *formattedPhoneNumber = [proposedText substringFromIndex:2]; // without +1 prefix
NSString *unformattedPhoneNumber = [formattedPhoneNumber stringByReplacingOccurrencesOfString:@"-" withString:@""]; // without hypens
// start with the prefix
NSMutableString *newText = [NSMutableString stringWithString:@"+1"];
for (NSInteger i = 0; i < [unformattedPhoneNumber length]; i++) {
if (i % 3 == 0) {
// add a - every 3 characters. add one at the beginning as well
[newText appendString:@"-"];
}
// add each digit from the unformatted phonenumber
[newText appendString:[unformattedPhoneNumber substringWithRange:NSMakeRange(i, 1)]];
}
textField.text = newText;
return NO;
}
這仍然是一個非常幼稚的實現。 它有兩個問題,例如,因為我們手動設置了textField的text
,所以光標將始終位於末尾。 因此,用戶無法輕松刪除字符串中間的數字。 當然,有一些解決方法。 selectedTextRange
將是要使用的屬性。 而且,您無法真正將電話號碼粘貼到該字段中。 用戶當然不能刪除連字符。
用戶鍵入時進行格式化往往會很快變得復雜,因為存在很多邊緣情況。 但這應該可以幫助您入門。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.