Monday, November 9, 2015

How to retrieve and select all labels in Swift

I've recently started doing Swift development, and was tasked with finding a way to select each label that was swiped over in an app. I made multiple attempts at this, first trying a gesture recognizer, and then trying to implement code in the touchesBegan and touchesMoved methods to no avail. I could select a single label, but couldn't get multiple without implementing a gesture recognizer for each label (and that would be extremely repetitive, extraneous code). After a ton of Googling, I finally asked for help in the Swift subreddit, which got me REALLY close. The only thing I was missing was how to get a collection of each label in the app.
My first thought was to create an outlet for each label, and then create an array containing a reference to each label and using that, but that would again be time consuming, and just didn't seem efficient to me. I asked the author of the Reddit response what he was using in his code as an allLabels() function, but didn't get a response there, so I kept Googling. After a couple more days, I finally came across this beautiful Stack Overflow. They were getting an array of buttons, but I assumed that I could apply the same code to labels and voila! Problem solved, and it's SO simple. The code I ended up with for getting an array of all labels is as follows:
private var labels:[UILabel] = [UILabel]()
    
    override func viewWillAppear(animated: Bool) {
        for v:AnyObject in self.view.subviews {
            if v is UILabel {
                labels.append(v as! UILabel)
            }
        }
    }
Hope this helps anyone doing a similar search!

No comments:

Post a Comment