我正在尝试在我的UIViewControllers的超级视图中找到我的UILabels.
这是我的代码:
这是我的代码:
- func watch(startTime:String,endTime:String) {
- if superview == nil {println("NightWatcher: No viewcontroller specified");return}
- listSubviewsOfView(self.superview!)
- }
- func listSubviewsOfView(view: UIView) {
- var subviews = view.subviews
- if (subviews.count == 0) { return }
- view.backgroundColor = UIColor.blackColor()
- for subview in subviews {
- if subview.isKindOfClass(UILabel) {
- // do something with label..
- }
- self.listSubviewsOfView(subview as UIView)
- }
- }
这是在Objective-C中推荐的方式,但是在Swift中我只得到UIViews和CALayer.我肯定在提供给这个方法的视图中有UILabel.我错过了什么?
我的UIViewController中的调用:
- NightWatcher(view: self.view).watch("21:00",endTime: "08:30") // still working on
解决方法
使用函数式编程概念可以更轻松地实现这一目标.
- let labels = self.view.subviews.flatMap { $0 as? UILabel }
- for label in labels {
- //Do something with label
- }