如何在swift中从视图中获取所有文本字段 [英] How to get all the textfields from a view in swift

查看:146
本文介绍了如何在swift中从视图中获取所有文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个超过15 UITextFields 的视图。我必须为所有 UITextFields 设置bottomBorder(扩展名)。我可以逐个为所有 UITextFields 设置它,它也可以。我想立刻为所有 UITextFields 设置底部边框。这是我正在尝试的代码,但似乎for循环没有执行。我甚至在 viewDidLayoutSubViews 中尝试了它,但是循环也没有在那里执行。

I have a view which has more than 15 UITextFields. I have to set bottomBorder(extension) for all the UITextFields. I can set it one by one for all the UITextFields and its working too. I want to set the bottom border for all the UITextFields at once. Here is the code I am trying but it seems like that for loop is not executing. I have even tried it in viewDidLayoutSubViews but for loop not executing there too.

 override func viewDidLoad() 
{
    super.viewDidLoad()

    /** setting bottom border of textfield**/

    for case let textField as UITextField in self.view.subviews {
        textField.setBottomBorder()
    }
}


推荐答案

我让它工作了,但仍然需要解释为什么有问题的代码不起作用

我从论坛的某个地方得到它,而不是完全可以归功于答案。

I made it working, but still need the explanation why the code in question is not working
I got it from somewhere on the forum, not exactle able to credit the answer.

/** extract all the textfield from view **/
func getTextfield(view: UIView) -> [UITextField] {
var results = [UITextField]()
for subview in view.subviews as [UIView] {
    if let textField = subview as? UITextField {
        results += [textField]
    } else {
        results += getTextfield(view: subview)
    }
}
return results  

在viewDidLoad或viewDidLayoutSubviews中调用上述函数。

Call the above function in viewDidLoad or viewDidLayoutSubviews.

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

/** setting bottom border to the textfield **/
    let allTextField = getTextfield(view: self.view)
    for txtField in allTextField
    {
        txtField.setBottomBorder()
    }
}

这篇关于如何在swift中从视图中获取所有文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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