Aggiungo questo Method al mio codice per formattare il campo di testo. Sto usando il codice qui sotto per provare ad aggiungere il metodo, ma non funziona, cosa sto facendo male?Aggiunta di un metodo al mio uitextfield nella cella?
file h
NSString* phone_;
UITextField* phoneFieldTextField;
@property (nonatomic,copy) NSString* phone;
di file .m
@synthesize phone = phone_;
ViewDidLoad{
self.phone = @"";
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
// Make cell unselectable and set font.
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.font = [UIFont fontWithName:@"ArialMT" size:13];
if (indexPath.section == 0) {
UITextField* tf = nil;
switch (indexPath.row) {
case 3: {
cell.textLabel.text = @"Phone" ;
tf = phoneFieldTextField = [self makeTextField:self.phone placeholder:@"xxx-xxx-xxxx"];
phoneFieldTextField.keyboardType = UIKeyboardTypePhonePad;
[self formatPhoneNumber:phoneFieldTextField.text deleteLastChar:YES];
[cell addSubview:phoneFieldTextField];
break ;
}
// Textfield dimensions
tf.frame = CGRectMake(120, 12, 170, 30);
// Workaround to dismiss keyboard when Done/Return is tapped
[tf addTarget:self action:@selector(textFieldFinished:) forControlEvents:UIControlEventEditingDidEndOnExit];
}
}
// Textfield value changed, store the new value.
- (void)textFieldDidEndEditing:(UITextField *)textField {
//Section 1.
if (textField == nameFieldTextField) {
self.name = textField.text ;
} else if (textField == addressFieldTextField) {
self.address = textField.text ;
} else if (textField == emailFieldTextField) {
self.email = textField.text ;
} else if (textField == phoneFieldTextField) {
self.phone = textField.text ;
}else if (textField == dateOfBirthTextField) {
self.dateOfBirth = textField.text ;
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString* totalString = [NSString stringWithFormat:@"%@%@",textField.text,string];
// if it's the phone number textfield format it.
if(textField.tag == 10) {
if (range.length == 1) {
// Delete button was hit.. so tell the method to delete the last char.
textField.text = [self formatPhoneNumber:totalString deleteLastChar:YES];
} else {
textField.text = [self formatPhoneNumber:totalString deleteLastChar:NO ];
}
return false;
}
return YES;
NSLog(@"Testing should change character in range");
}
-(NSString*) formatPhoneNumber:(NSString*) simpleNumber deleteLastChar:(BOOL)deleteLastChar {
if(simpleNumber.length == 0) return @"";
// use regex to remove non-digits(including spaces) so we are left with just the numbers
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[\\s-\\(\\)]" options:NSRegularExpressionCaseInsensitive error:&error];
simpleNumber = [regex stringByReplacingMatchesInString:simpleNumber options:0 range:NSMakeRange(0, [simpleNumber length]) withTemplate:@""];
// check if the number is to long
if(simpleNumber.length>10) {
// remove last extra chars.
simpleNumber = [simpleNumber substringToIndex:10];
}
if(deleteLastChar) {
// should we delete the last digit?
simpleNumber = [simpleNumber substringToIndex:[simpleNumber length] - 1];
}
// 123 456 7890
// format the number.. if it's less then 7 digits.. then use this regex.
if(simpleNumber.length<7)
simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:@"(\\d{3})(\\d+)"
withString:@"($1) $2"
options:NSRegularExpressionSearch
range:NSMakeRange(0, [simpleNumber length])];
else // else do this one..
simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:@"(\\d{3})(\\d{3})(\\d+)"
withString:@"($1) $2-$3"
options:NSRegularExpressionSearch
range:NSMakeRange(0, [simpleNumber length])];
if (simpleNumber.length == 10 && deleteLastChar == NO) { [self resignFirstResponder];}
return simpleNumber;
NSLog(@"Testing format phone number");
}
#pragma mark - TextField
-(UITextField*) makeTextField: (NSString*)text
placeholder: (NSString*)placeholder {
UITextField *tf = [[UITextField alloc] init];
tf.placeholder = placeholder;
tf.text = text ;
tf.autocorrectionType = UITextAutocorrectionTypeNo ;
tf.autocapitalizationType = UITextAutocapitalizationTypeNone;
tf.adjustsFontSizeToFitWidth = YES;
tf.returnKeyType = UIReturnKeyDone;
tf.textColor = [UIColor colorWithRed:56.0f/255.0f green:84.0f/255.0f blue:135.0f/255.0f alpha:1.0f];
return tf ;
}
In primo luogo, la mia domanda nel titolo dice esattamente ciò che non funziona. In secondo luogo, il "bug" non si trova in 'textField: shouldChangeCharactersInRange:' perché non è nemmeno il mio metodo, e Dana in basso è riuscito a farlo funzionare correttamente. Ho impostato il textField.tag di conseguenza. Ho anche registrato ciò che viene chiamato.Il mio caso 3 viene chiamato correttamente e tutto funziona bene con la cella e il segnaposto. – Jason
Il problema è la formattazione della cella per utilizzare il metodo del numero di telefono che ho trovato su questo sito e referenziato correttamente. 'superView didLoad' è anche nel mio' viewDidLoad' non è necessario per questa domanda. Sto anche usando gli storyboard come suggerivi. – Jason
Ciao @ Jason hai scaricato e verificato la mia app di esempio? Ok la tua impostazione del tag hai impostato anche il delegato? Puoi includere anche il codice makeTextField nella tua domanda di cui sopra. Grazie – GayleDDS