Scroll through subview to check for empty UITextField - Swift

I am wondering how to significantly convert the objective c code below to swift.

This will go through all the child objects in my desired view, check to see if they are text fields, and then check to see if they are empty.

for (UIView *view in contentVw.subviews) { NSLog(@"%@", view); if ([view isKindOfClass:[UITextField class]]) { UITextField *textfield = (UITextField *)view; if (([textfield.text isEqualToString:""])) { //show error return; } } } 

This is where I am with quick translation:

 for view in self.view.subviews as [UIView] { if view.isKindOfClass(UITextField) { //... } } 

Any help would be great!

+27
ios for-loop swift fast-enumeration
Aug 02 '14 at 18:06
source share
2 answers

Swift 5 and Swift 4: - A very simple answer that you can easily understand: - You can handle all kinds of objects, such as UILable, UITextfields, UIButtons, UIView, UIImages. any kind of items, etc.

 for subview in self.view.subviews { if subview is UITextField { //MARK: - if the sub view is UITextField you can handle here if subview.text == "" { //MARK:- Handle your code } } if subview is UIImageView { //MARK: - check image if subview.image == nil { //Show or use your code here } } } //MARK:- You can use it any where, where you need it //Suppose i need it in didload function we can use it and work it what do you need override func viewDidLoad() { super.viewDidLoad() for subview in self.view.subviews { if subview is UITextField { //MARK: - if the sub view is UITextField you can handle here if subview.text == "" { //MARK:- Handle your code } } if subview is UIImageView { //MARK: - check image if subview.image == nil { //Show or use your code here } } } } 
+5
Mar 02 '18 at 21:07
source share

Update for Swift 2 (and later): With Swift 2 / Xcode 7 this can be simplified.

  • Due to Objective-C "light generics" self.view.subviews already declared as [UIView] in Swift, so casting is no longer required.
  • Enumeration and optional casting can be combined with a for-loop with a case pattern.

This gives:

 for case let textField as UITextField in self.view.subviews { if textField.text == "" { // show error return } } 



Old answer for Swift 1.2:

In Swift, this is beautifully done with the optional downt as? :

 for view in self.view.subviews as! [UIView] { if let textField = view as? UITextField { if textField.text == "" { // show error return } } } 

See "Downcasting" in Swift's book.

+78
02 Aug '14 at 18:13
source share



All Articles