-2

i am working on the Registration form , after filling multiple textfields when the user taps on the button the textfield should be clear.

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
Azam
  • 13
  • 3

3 Answers3

5

If you don't want to use UITextField collection, you can use this,

@IBAction func buttontapped(_ sender: Any) {
    self.view.subviews.forEach({ item in
        if item.isKind(of: UITextField.self) {
            let txtItem = item as! UITextField
            txtItem.text = ""
        }
    })
}

UPDATE as @vacawama suggested,

@IBAction func buttontapped(_ sender: Any) {
    for case let txtItem as UITextField in self.view.subviews {
        txtItem.text = ""
    }
}

Assumption: All textfields are subviews of self.view directly. if textfields are subview of other customview, you should use that customview instead of self.view

PPL
  • 6,357
  • 1
  • 11
  • 30
3

swift

create the IBOutletCollections or add all your textfield to one array for e.g

 @IBOutlet var storeAllTexts: [UITextField]!

on your button action method, call the following

   storeAllTexts.forEach { $0.text = "" }

objective C

create the IBOutletCollections

 @property (nonatomic, strong) IBOutletCollection(UITextField) NSArray *storeAllTexts;

on your button action

 for (UITextField *getCurrentText in self.storeAllTexts) {
  getCurrentText.text = @"";
}

for sample your get the SO duplicate answer

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
1

For Objective C

for (id view in [self.view subviews])                                              
{
    if ([view isKindOfClass:[UITextField class]])                                       
    {
        UITextField *textField = (UITextField *)view;
        textField.text = @"";
    }
 }
Kalpesh Panchasara
  • 1,730
  • 2
  • 15
  • 27