How do I show and/or hide a subview using swift

2019-03-14 10:41发布

问题:

So I've created a ViewControl in my storyboard that has 3 subviews. Each one represents a different view I want to show depending on which table row was selected on the previous screen (NavControl). I start with all of the subviews hidden via the Attributes Inspector's 'hidden' attribute being checked. All of the objects within each of these views are NOT hidden, but are being hidden because the subview itself is hidden (obviously). Thinking I could use the tag attribute I've given each of the three subviews a tag (0, 1 and 2), but can't figure out how to use that either (just in case this is useful as providing me with an option of how to do this I wanted to mention it here).

So, how the heck do I show and then hide any of these subviews? I don't want to go through each object in a subview and toggle its hidden property to true/false I feel like I should just be able to 'show/hide' the entire subview. thus achieving the same result, but much more succinctly.

I can't find anything that will help me via web searches or stackoverflow searches.

My code is very simple. I capture the row that was selected in the previous screen and pass it to a variable on the details screen that contains the subviews. I know this is working because I've set up println()'s on the details screens viewDidLoad function. So now all I have to do is going into each of these conditions and tell it which subview to show and/or hide.

Thanks I appreciate all of this communities help! I'd be lost without it.

回答1:

You should create IBOutlets for each of the three subviews. Then you can show/hide each of them directly from those references. If you hide a view, it will automatically hide its subviews.

Once you have an outlet for the view, you can do this: viewYouWantToHide.isHidden = true



回答2:

Use this to hide a view in swift

viewVar.isHidden = true


回答3:

If you have tags for each view you can hide and display them using:

Objective C

For Hiding:

[[self.view viewWithTag:1] setHidden:YES];

Showing:

[[self.view viewWithTag:1] setHidden:NO];

In Swift:

Hiding:

self.view.viewWithTag(1)?.hidden = true

Showing:

self.view.viewWithTag(1)?.hidden = false

NOTE: Replace 1 with your tag value.



回答4:

however the fact that isHidden is a naming convention for checking the status and is a getter method but despite that fact in swift we use it as setter and getter property

view.isHidden = true


标签: ios swift uiview