title: prefix a text in textfield objective c iOS
body: <p>How to set a prefix string like this : @test.com (fixed string and cannot change) in textfield objective c iOS and user can fill in the userid?
  So as a result: userid@test.com</p>
  
  <pre><code>-(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 &lt;= substringRange.location &amp;&amp; range.location substringRange.location + substringRange.length) {
          return NO;
      }
  
      return YES;
  }
  </code></pre>