I\'m using the code below to try and have textField2
\'s text content get updated to match textField1
\'s whenever the user types in textField1
My solution is to use UITextFieldTextDidChangeNotification
.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(copyText:) name:UITextFieldTextDidChangeNotification object:nil];
Don't forget to call [[NSNotificationCenter defaultCenter] removeObserver:self];
in dealloc
method.
Swift version for it :
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
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSLog(@"%@",searchStr);
return YES;
}
In Swift(4), without NSString
(pure Swift):
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let textFieldString = textField.text, let swtRange = Range(range, in: textFieldString) {
let fullString = textFieldString.replacingCharacters(in: swtRange, with: string)
print("FullString: \(fullString)")
}
return true
}
As an extension:
extension UITextField {
func fullTextWith(range: NSRange, replacementString: String) -> String? {
if let fullSearchString = self.text, let swtRange = Range(range, in: fullSearchString) {
return fullSearchString.replacingCharacters(in: swtRange, with: replacementString)
}
return nil
}
}
// Usage:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let textFieldString = textField.fullTextWith(range: range, replacementString: string) {
print("FullString: \(textFieldString)")
}
return true
}
-shouldChangeCharactersInRange
gets called before text field actually changes its text, that's why you're getting old text value. To get the text after update use:
[textField2 setText:[textField1.text stringByReplacingCharactersInRange:range withString:string]];
Instead of using the UITextFieldDelegate, try to use "Editing Changed" event of UITextField.