iosfor-loopswiftfast-enumeration

Loop through subview to check for empty UITextField - Swift


I"m wondering how to essentially transform the objective c code below into swift.

This will loop through all the subviews on my desired view, check if they are textfields, and then check if they are empty of not.

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

Here is where i am with swift translation so far:

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

    }
}

Any help would be great!


Solution

  • Swift 5 and Swift 4: - A Very simple answer you can understand easyly : - You can handle all kind of Objects like UILable, UITextfields, UIButtons, UIView, UIImages . any kind of objecs 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
                    }
                }
            }
        }