Swift - UIViews以编程方式订购

时间:2017-11-21 19:37:10

标签: ios swift uiview programmatically

我在一个ViewController中有几个UIView层。 Several UIViews layers

如何以编程方式确定UIView的顺序?

2 个答案:

答案 0 :(得分:3)

我找到了解决方案......

在UIView文档中,列出了几种用于操纵子视图顺序的方法:

bringSubviewToFront(_:)

sendSubviewToBack(_:)

removeFromSuperview()

insertSubview(_:atIndex:)

insertSubview(_:aboveSubview:)

insertSubview(_:belowSubview:)

exchangeSubviewAtIndex(_:withSubviewAtIndex:)

在Swift 4.0中

view.sendSubview(toBack:yourUIView)

view.bringSubview(toFront:yourUIView)

答案 1 :(得分:1)

view.subviews数组中,视图从最后面到最前面排序。

例如,这里有3个子视图添加到空视图中。

view.addSubview(UILabel())
view.addSubview(UIButton())
view.addSubview(UITextField())

使用以下代码打印子视图

for view in view.subviews {
    print(view.debugDescription)
}

有输出

<UILabel: 0x7feef00042e0; frame = (0 0; 0 0); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x60400008c210>>
<UIButton: 0x7feef00045c0; frame = (0 0; 0 0); opaque = NO; layer = <CALayer: 0x604000222300>>
<UITextField: 0x7feeef02c800; frame = (0 0; 0 0); text = ''; opaque = NO; gestureRecognizers = <NSArray: 0x60800005b090>; layer = <CALayer: 0x604000222280>>

重新排序视图后,view.subviews中的排名会发生变化

if let button = view.subviews.first(where: { $0 is UIButton }) {
    view.bringSubview(toFront: button)
}

现在,打印视图,输出

<UILabel: 0x7feef00042e0; frame = (0 0; 0 0); userInteractionEnabled = NO; layer = <_UILabelLayer: 0x60400008c210>>
<UITextField: 0x7feeef02c800; frame = (0 0; 0 0); text = ''; opaque = NO; gestureRecognizers = <NSArray: 0x60800005b090>; layer = <CALayer: 0x604000222280>>
<UIButton: 0x7feef00045c0; frame = (0 0; 0 0); opaque = NO; layer = <CALayer: 0x604000222300>>