i am working on the Registration form , after filling multiple textfields when the user taps on the button the textfield should be clear.
Asked
Active
Viewed 103 times
-2
-
5show your tried code, – Anbu.Karthik Jun 01 '18 at 10:10
-
1if you want to clear all textfields or else particular textfield – Anbu.Karthik Jun 01 '18 at 10:10
-
i want to clear all textfields – Azam Jun 01 '18 at 10:12
-
when i tap on the button – Azam Jun 01 '18 at 10:13
-
Possible duplicate of [How to delete the contents of a UITextField programmatically?](https://stackoverflow.com/questions/6560888/how-to-delete-the-contents-of-a-uitextfield-programmatically) – Hardik Bar Jun 01 '18 at 10:17
3 Answers
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
-
-
-
`for case let txtItem as UITextField in self.view.subviews { txtItem.text = "" }` – vacawama Jun 01 '18 at 10:16
-
-
1In either case, OP might have to substitute another view for `self.view` if the `UITextField`s are subviews of another view (like a `UIScrollView` or `UIStackView`). – vacawama Jun 01 '18 at 10:22
-
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