循环遍历子视图以检查空的UITextField - Swift

Rya*_*yan 27 for-loop fast-enumeration ios swift

我想知道如何将下面的客观c代码转换成swift.

这将遍历我想要的视图上的所有子视图,检查它们是否是文本字段,然后检查它们是否为空.

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

到目前为止,这里是我快速翻译的地方:

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

    }
}
Run Code Online (Sandbox Code Playgroud)

任何帮助都会很棒!

Mar*_*n R 78

Swift 2(及更高版本)的更新:从Swift 2/Xcode 7开始,这可以简化.

  • 由于Objective-C"轻量级泛型" self.view.subviews 已经[UIView]在Swift中声明,因此不再需要强制转换.
  • 枚举和可选的强制转换可以与带有案例模式的for循环组合.

这给出了:

for case let textField as UITextField in self.view.subviews {
    if textField.text == "" {
        // show error
        return
    }
}
Run Code Online (Sandbox Code Playgroud)

Swift 1.2的旧答案:

在Swift中,使用可选的向下转换操作符可以很好地完成as?:

for view in self.view.subviews as! [UIView] {
    if let textField = view as? UITextField {
        if textField.text == "" {
            // show error
            return
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请参阅 Swift书中的"向下转发".


Sha*_*med 5

Swift 5和Swift 4:-一个非常简单的答案,您可以轻松理解:-您可以处理各种对象,例如UILable,UITextfields,UIButtons,UIView,UIImages。任何种类的对象等

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
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)