I\'m trying to show changes made to a UITextField
on a separate UILabel
. Is there a way to capture full text of the UITextField
after
UITextField
and UILabel
to storyboard / nibIBOutlet
for UILabel
(Here I have used myLabel)UITextFieldDelegate
to file owner, also implement the same delegate in .h fileUse these lines of code:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
[self updateTextLabelsWithText: newString];
return YES;
}
-(void)updateTextLabelsWithText:(NSString *)string
{
[myLabel setText:string];
}
Hope this helps.
In Swift 3.0:
Some of these solutions were one character behind, or for earlier versions of Swift and Obj-C. Here is what I am using for Swift 3.0
In the class I declared a placeholder to store the text.
var tempName = ""
In ViewDidLoad I used:
nameField.addTarget(self, action: #selector(typingName), for: .editingChanged)
Then I made a function called:
func typingName(textField:UITextField){
if let typedText = textField.text {
tempName = typedText
print(tempName)
}
}
Swift with addTarget Swift 2.0+
titleTextField.addTarget(self, action: #selector(textFieldTyping), forControlEvents: .EditingChanged)
And implement selector
func textFieldTyping(textField:UITextField)
{
//Typing
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == yourTextFieldOutletName
{
if yourTextFieldOutletName.isEmpty == false
{
youtlabelname.text = yourTextFieldOutletName.text!
}
}
return true
}
func textViewDidEndEditing(_ textView: UITextView) {
if textField == yourTextFieldOutletName
{
if yourTextFieldOutletName.isEmpty == false
{
youtlabelname.text = yourTextFieldOutletName.text!
}
}
}
Simply handle the "Editing Changed" event
[textField addTarget:self
action:@selector(editingChanged:)
forControlEvents:UIControlEventEditingChanged];
and the selector:
-(void) editingChanged:(id)sender {
// your code
}
You can do this manually, or with the storyboard by CTRL-Dragging the "Editing changed" Sent event to your .h, creating the editingChanged method for you.
In Swift 2.0+
class CheckInViewController: UIViewController, UITextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
yourTextField.delegate = self
}
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
var updatedTextString : NSString = textField.text as NSString
updatedTextString = updatedTextString.stringByReplacingCharactersInRange(range, withString: string)
self.methodYouWantToCallWithUpdatedString(updatedTextString)
return true
}
}
Hope it helps you swift pioneers