Find UILabel in UIView in Swift

I am trying to find my UILabels in my overview of my UIViewControllers. This is my code:

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) } } 

This is how it is recommended in Objective-C, but in Swift I get nothing but UIViews and CALayer. I definitely have UILabels in the view that is provided to this method. What am I missing?

Calling my UIViewController:

  NightWatcher(view: self.view).watch("21:00", endTime: "08:30") // still working on 
+6
source share
2 answers

Using the concepts of functional programming, you can achieve this a lot easier.

 let labels = self.view.subviews.flatMap { $0 as? UILabel } for label in labels { //Do something with label } 
+2
source

Here is a version that will return an Array all UILabel in any view you pass:

 func getLabelsInView(view: UIView) -> [UILabel] { var results = [UILabel]() for subview in view.subviews as [UIView] { if let labelView = subview as? UILabel { results += [labelView] } else { results += getLabelsInView(view: subview) } } return results } 

You can then iterate over them to do whatever you want:

 override func viewDidLoad() { super.viewDidLoad() let labels = getLabelsInView(self.view) for label in labels { println(label.text) } } 
+10
source

Source: https://habr.com/ru/post/974121/


All Articles