如何在iOS的文本字段目标c中设置@ test.com(固定字符串,不能更改)这样的前缀字符串,并且用户可以填写userid? 结果是:userid@test.com
-(void)viewDidLoad {
[super viewDidLoad];
[self.emailField setDelegate:self];
[self.emailField setSpellCheckingType:UITextSpellCheckingTypeNo];
[self setShouldUpdateAttributes:YES];
NSString *fixedString = @"@test.com";
[self.emailField setText:fixedString];
[self.emailField addTarget:self action:@selector(textFieldDidChangeText:) forControlEvents:UIControlEventEditingChanged];
[self textFieldDidChangeText:self.emailField];
}
-(void)textFieldDidChangeText:(UITextField *)sender
{
if (self.shouldUpdateAttributes) {
[self setShouldUpdateAttributes:NO];
NSString *fixedString = @"@test.com";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:sender.text];
[attributedString setAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]} range:NSMakeRange(0, fixedString.length)];
[attributedString setAttributes:@{NSForegroundColorAttributeName: [UIColor darkGrayColor]} range:NSMakeRange(fixedString.length, sender.text.length - fixedString.length)];
[sender setAttributedText:attributedString];
[sender resignFirstResponder];
[sender becomeFirstResponder];
}
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
[self setShouldUpdateAttributes:YES];
NSString *fixedString = @"@test.com";
NSRange substringRange = [textField.text rangeOfString:fixedString];
if (range.location <= substringRange.location && range.location substringRange.location + substringRange.length) {
return NO;
}
return YES;
}