Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Retrieving subviews

In my application I am adding labels to the view and then I am attempting to clear particular labels from the view when a button is clicked and am running into an error when trying to retrieve the subviews:

class FirstViewController: UIViewController {

     @IBAction func btnAddTask_Click(sender: UIButton){

          var subViews = self.subviews.copy()

    }
 }

I get the error:

'FirstViewController' does not have a member named 'subviews'

How can I get the subviews of the current view?

like image 901
user2961953 Avatar asked Sep 28 '14 14:09

user2961953


People also ask

How do I get Subviews in UIView Swift?

If you need a quick way to get hold of a view inside a complicated view hierarchy, you're looking for viewWithTag() – give it the tag to find and a view to search from, and this method will search all subviews, and all sub-subviews, and so on, until it finds a view with the matching tag number.

How do I remove all Subviews from a view in Swift?

This should be the simplest solution. This is definitely the simplest way... removeFromSuperview is automatically called for each view that is no longer in the subviews array.

How do I remove all Subviews from UIView?

For UIView, you can safely use makeObjectsPerformSelector: because the subviews property will return a copy of the array of subviews. Using makeObjectsPerformSelector method you can remove all the subviews but, not subviews based on conditions.


2 Answers

UIViewController doesn't have a subviews property. It has a view property, which has a subviews property:

for subview in self.view.subviews {
   // Manipulate the view
}

But typically this is not a good idea. You should instead put the labels you want into an IBOutletCollection and iterate over that. Otherwise you've very tied to the exact set of subviews (which may change).

To create the IBOutletCollection, select all the labels you want in IB, and control-drag them to the source code. It should ask if you want to make a collection array. (Note that there is no promise on the order of this array.)

like image 175
Rob Napier Avatar answered Oct 18 '22 18:10

Rob Napier


For find all subviews from your view you can use this code:

for subview in self.view.subviews {
   // Use your subview as you want
}

But for use it, you must identify view what you need. You can mark any element, what you create, with special Identifier like this:

myButton.restorationIdentifier = "mySpecialButton";

And after that you can find your element use this structure:

for view in view.subviews {
                if (view.restorationIdentifier == "mySpecialButton") {
                    print("I FIND IT");
                    view.removeFromSuperview();
                }
            }

:)

like image 28
Ivan Trubnikov Avatar answered Oct 18 '22 20:10

Ivan Trubnikov