Find UILabel in UIView in Swift

2020-03-15 01:39发布

I'm trying to find my UILabels in my superview 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 to in Objective-C, but in Swift I get nothing but UIViews and CALayer. I definitely have UILabels in the view that is supplied to this method. What am I missing?

The call in my UIViewController:

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

4条回答
神经病院院长
2楼-- · 2020-03-15 01:58

Swift 4

Adepting mKane's answer you can use this code:

let labels = self.view.subviews.compactMap { $0 as? UILabel }

for label in labels {
   // do whatever
}
查看更多
啃猪蹄的小仙女
3楼-- · 2020-03-15 01:59

You could set a tag to your UILabel in the Storyboard or programmatically using:

myLabel.tag = 1234 

Then, to find it use:

let myLabel = view.viewWithTag(1234)

查看更多
啃猪蹄的小仙女
4楼-- · 2020-03-15 02:02

Using functional programming concepts you can achieve this much easier.

let labels = self.view.subviews.flatMap { $0 as? UILabel }

for label in labels {
//Do something with label
}
查看更多
三岁会撩人
5楼-- · 2020-03-15 02:15

Here's a version that will return an Array of all the UILabel views in whatever view you pass in:

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
}

Then you can iterate over them to do whatever you'd like:

override func viewDidLoad() {
    super.viewDidLoad()

    let labels = getLabelsInView(self.view)
    for label in labels {
        println(label.text)
    }
}
查看更多
登录 后发表回答