使用`textField:shouldChangeCharactersInRange:`,我如何获取包含当前input字符的文本?
我使用下面的代码来尝试使textField2的文本内容得到更新,以便每当用户inputtextField1时匹配textField1 。 
 - (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string { if (theTextField == textField1){ [textField2 setText:[textField1 text]]; } } 
然而,我观察到的产出是…
textField2是“12”,当textField1是“123”
textField2是“123”,当textField1是“1234”
…当我想要的是:
textField2是“123”,当textField1是“123”
textField2是“1234”,当textField1是“1234”
我究竟做错了什么?
  在文本字段实际上改变其文本之前调用了更改-shouldChangeCharactersInRange ,这就是为什么你会得到旧的文本值。 要获取更新后的文本使用: 
 [textField2 setText:[textField1.text stringByReplacingCharactersInRange:range withString:string]]; 
 -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string]; NSLog(@"%@",searchStr); return YES; } 
尝试使用UITextField的“Editing Changed”事件,而不是使用UITextFieldDelegate。
Swift 3
根据接受的答案,下面的内容应该在Swift 3中工作:
 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let newString = NSString(string: textField.text!).replacingCharacters(in: range, with: string) return true } 
注意
  String和NSString都有一个名为replacingCharacters:inRange:withString方法replacingCharacters:inRange:withString 。 然而,正如预期的那样,前者期望Range一个实例,而后者期望一个NSRange的实例。  textField委托方法使用NSRange实例,因此在这种情况下使用NSString 。 
Swift版本:
 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if string == " " { return false } let userEnteredString = textField.text var newString = (userEnteredString! as NSString).stringByReplacingCharactersInRange(range, withString: string) as NSString print(newString) return true } 
这是你需要的代码,
 if ([textField isEqual:self.textField1]) textField2.text = [textField1.text stringByReplacingCharactersInRange:range withString:string]; 
使用警卫
 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { guard case let textFieldString as NSString = textField.text where textFieldString.stringByReplacingCharactersInRange(range, withString: string).length <= maxLength else { return false } return true } 
 我的解决scheme是使用UITextFieldTextDidChangeNotification 。 
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(copyText:) name:UITextFieldTextDidChangeNotification object:nil]; 
 不要忘记调用[[NSNotificationCenter defaultCenter] removeObserver:self]; 在dealloc方法中。 
如果你需要用这个replacetextfield文本,你可以使用我的解决scheme(Swift 3): https : //gist.github.com/Blackjacx/2198d86442ec9b9b05c0801f4e392047
 replace之后,您可以获取textField.text来检索组合文本。