How to loop through Outlets of a UIViewController with Swift

时间秒杀一切 提交于 2019-12-28 04:21:11

问题


I'm wondering, if it's possible to loop through all outlets of a UIViewController with swift.

Specificly, I want to check if every textfield is filled by the user.


回答1:


This is what Outlet Collections are for. Drag all your textfields in the same Outlet Collection in InterfaceBuilder and create an @IBOutlet to that collection in your class file:

To create the outlet collection in InterfaceBuilder, ctrl-drag from the first UITextField to your class file in the assistant editor. Then choose Outlet Collection:

ctrl-drag the next UITextField on that @IBOutlet to add it to the collection:

Repeat that for all your textFields.

@IBOutlet var textFields: [UITextField]!

func checkTextFields() {
    for textField in self.textFields {
        ... // do your checks
    }
}



回答2:


I think you have to manually do it, or add them to array and loop through that array or you can loop through all subviews of your view and check if it's textfield.

for view in self.view.subviews as [UIView] {
    if let textField = view as? UITextField {
        if textField.text == "" {
            // textfield is empty
            return
        }
    }
}


来源:https://stackoverflow.com/questions/29167294/how-to-loop-through-outlets-of-a-uiviewcontroller-with-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!