Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I bring a view in front of another view, in Swift?

Below are how my views are organized in IB, top->bottom when the app is started.

The user can do something to make "Category Table View Header" temporarily expand over "Name View" - however once doing so, the .TouchDown action assigned to "Category Table View Header" no longer works wherever it overlaps with "Name View" (i.e., the user can tap the header anywhere it doesn't overlap with name view and it still works).

enter image description here

I know that may be confusing, so I drew out some boxes. On the left is the original, right is after user action - problem is on the right the action on the red box only works if the user taps the bottom half, not the top half.

enter image description here

My guess is its because the header is lower in the view hierarchy than the name view, but it would be hard for me to change that without messing around with a bunch of constraints.

I also tried setting nameView.hidden = true, but that doesn't work.

like image 426
vk2015 Avatar asked Aug 05 '16 03:08

vk2015


People also ask

What is super view in Swift?

The superview is the immediate ancestor of the current view. The value of this property is nil when the view is not installed in a view hierarchy. To set the value of this property, use the addSubview(_:) method to embed the current view inside another view.

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.

What is addSubview?

Adds a view to the end of the receiver's list of subviews.


1 Answers

If you want to bring a subview to the front, you can use:

SWIFT 4 + UPDATE

self.view.bringSubviewToFront(yourView) 

SWIFT 3 UPDATE

self.view.bringSubview(toFront: yourView) 

Send view to back:-

SWIFT 4+ UPDATE

self.view.sendSubviewToBack(yourView) 

SWIFT 3 UPDATE

self.view.sendSubview(toBack: yourView) 

SWIFT 4+ UPDATE - INSERT VIEW ON SPECIFIC LOCATION IN THE STACK

 parentView.insertSubview(yourView, belowSubview: requiredViewOnStack)  parentView.insertSubview(yourView, aboveSubview: requiredViewOnStack) 
like image 137
Chathuranga Silva Avatar answered Sep 21 '22 01:09

Chathuranga Silva