Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the z index or stack order of UIView?

I've stacked a UIView on top of an existing controller in an effort to create a gradient layer. However, when I load the view the new UIView (naturally) is on top of everything.

Relevant Code:

class ViewController: UIViewController {      @IBOutlet weak var myGradientView: GradientView!      override func viewDidLoad() {         super.viewDidLoad()                 }      override func viewDidLayoutSubviews() {         self.myGradientView.gradientWithColors(UIColor.whiteColor(), UIColor.blueColor())     } } 

I've done some searching and I found an answer in Objective-C that explains to use:

[parentView bringSubviewToFront:view];

I don't know objective-c and am fairly new to Swift, if someone could shine some light on this I would appreciate it.

My Question:

How do I change the z index or stack order of a UIView in Swift?

like image 785
Dan Beaulieu Avatar asked May 12 '15 23:05

Dan Beaulieu


People also ask

What is Z index in Swift?

Discussion. This property is used to determine the front-to-back ordering of items during layout. Items with higher index values appear on top of items with lower values. Items with the same value have an undetermined order. The default value of this property is 0.

What is layer Swift?

Overview. Layers are often used to provide the backing store for views but can also be used without a view to display content. A layer's main job is to manage the visual content that you provide but the layer itself has visual attributes that can be set, such as a background color, border, and shadow.


1 Answers

I would recommend looking in the UIView documentation, where are several methods listed for the manipulation of the order of subviews:

bringSubviewToFront(_:) sendSubviewToBack(_:) removeFromSuperview() insertSubview(_:atIndex:) insertSubview(_:aboveSubview:) insertSubview(_:belowSubview:) exchangeSubviewAtIndex(_:withSubviewAtIndex:) 

In your situation, you could try:

self.view.sendSubviewToBack(myGradientView) // self is your view controller in this case. 

Alternatively, because you created the myGradientView in IB, you could change the view hierarchy to change which views appeared on top. Here's a picture to illustrate:

enter image description here

Hope that helps.

like image 191
ABakerSmith Avatar answered Oct 15 '22 00:10

ABakerSmith