通过子视图循环检查空的UITextField - Swift [英] Loop through subview to check for empty UITextField - Swift

查看:175
本文介绍了通过子视图循环检查空的UITextField - Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这将遍历所需的视图上的所有子视图,检查它们是否是textfields,然后检查是否为空。



$ p $ for(UIView * view in contentVw.subviews){$ b $如果((view([view isKindOfClass:[UITextField class]]){
UITextField * textfield =(UITextField *)view;
if(( [textfield.text isEqualToString:])){
// show error
return;
}
}
}

  $ b 

code>在self.view.subviews中查看为[UIView] {
如果view.isKindOfClass(UITextField){
// ...

}




$ b

任何帮助都会很棒!

解决方案

Swift 2(及更高版本)的更新:由于Objective-C是轻量级的泛型,所以


  • > self.view.subviews
    已经在Swift中声明为 [UIView] ,因此不需要强制转换

  • 枚举和可选的转换可以与一个for-loop
    和一个case-pattern组合在一起。



这给:

 用于在self.view.subviews中使用textField作为UITextField { b $ b if textField.text =={
// show error
return
}
}



Swift 1.2的旧答案:


在Swift中,使用可选的downcast 运算符作为

 作为self.view.subviews中的视图! [UIView] {
如果让textField =查看为? UITextField {
if textField.text =={
// show error
return
}
}
}

请参阅Downcasting Swift book中的

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!

解决方案

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

  • Due to the Objective-C "lightweight generics", self.view.subviews is already declared as [UIView] in Swift, therefore the cast is not necessary anymore.
  • Enumeration and optional cast can be combined with to 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 nicely done with the optional downcast operator as?:

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

See "Downcasting" in the Swift book.

这篇关于通过子视图循环检查空的UITextField - Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆