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

时间:2015-05-12 23:13:30

标签: swift uiview ios8 z-index

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:

data2:[{x:4,y:11,sz:9,color:"green"},{x:11,y:17,sz:11,color:"green"}];

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?

2 个答案:

答案 0 :(得分:68)

我建议您查看UIView documentation,其中列出了几种方法来操纵子视图的顺序:

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

在您的情况下,您可以尝试:

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

或者,因为您在IB中创建了myGradientView,您可以更改视图层次结构以更改顶部显示的视图。这是一张图片来说明:

enter image description here

希望有所帮助。

答案 1 :(得分:6)

上面的答案

bringSubviewToFront(_:) sendSubviewToBack(_:)

已更改:

在Swift 3.0中

view.sendSubview(toBack:yourUIView)
view.bringSubview(toFront:yourUIView)