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
.
- (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {
if (theTextField == textField1){
[textField2 setText:[textField1 text]];
}
}
However, the output I observe is that...
textField2 is "12", when textField1 is "123"
textField2 is "123", when textField1 is "1234"
... when what I want is:
textField2 is "123", when textField1 is "123"
textField2 is "1234", when textField1 is "1234"
What am I doing wrong?
In Swift(4), without
NSString
(pure Swift):use guard
If you need to replace the textfield text with this you can use my solution (Swift 3): https://gist.github.com/Blackjacx/2198d86442ec9b9b05c0801f4e392047
After the replacement you can just get
textField.text
to retrieve the composed text.Swift 3
Based on the accepted answer, the following should work in Swift 3:
Note
Both
String
andNSString
have methods calledreplacingCharacters:inRange:withString
. However, as expected, the former expects an instance ofRange
, while the latter expects an instance ofNSRange
. ThetextField
delegate method uses anNSRange
instance, thus the use ofNSString
in this case.Swift version for it :