ios – 在Swift的UIView中找到UILabel

前端之家收集整理的这篇文章主要介绍了ios – 在Swift的UIView中找到UILabel前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在我的UIViewControllers的超级视图中找到我的UILabels.
这是我的代码
  1. func watch(startTime:String,endTime:String) {
  2. if superview == nil {println("NightWatcher: No viewcontroller specified");return}
  3.  
  4. listSubviewsOfView(self.superview!)
  5.  
  6. }
  7.  
  8. func listSubviewsOfView(view: UIView) {
  9. var subviews = view.subviews
  10.  
  11. if (subviews.count == 0) { return }
  12.  
  13. view.backgroundColor = UIColor.blackColor()
  14.  
  15. for subview in subviews {
  16. if subview.isKindOfClass(UILabel) {
  17. // do something with label..
  18. }
  19. self.listSubviewsOfView(subview as UIView)
  20. }
  21. }

这是在Objective-C中推荐的方式,但是在Swift中我只得到UIViews和CALayer.我肯定在提供给这个方法的视图中有UILabel.我错过了什么?

我的UIViewController中的调用

  1. NightWatcher(view: self.view).watch("21:00",endTime: "08:30") // still working on

解决方法

使用函数式编程概念可以更轻松地实现这一目标.
  1. let labels = self.view.subviews.flatMap { $0 as? UILabel }
  2.  
  3. for label in labels {
  4. //Do something with label
  5. }

猜你在找的iOS相关文章