Swift -UI视图顺序编程

iecba09b  于 2023-05-05  发布在  Swift
关注(0)|答案(2)|浏览(148)

我在一个ViewController中有几个UIView层。

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

uyhoqukh

uyhoqukh1#

我找到了解决办法。。
在UIView文档中,列出了几种用于操作子视图顺序的方法:

bringSubviewToFront(_:)

sendSubviewToBack(_:)

removeFromSuperview()

insertSubview(_:atIndex:)

insertSubview(_:aboveSubview:)

insertSubview(_:belowSubview:)

exchangeSubviewAtIndex(_:withSubviewAtIndex:)

Swift 4.0

view.sendSubview(toBack:yourUIView)

view.bringSubview(toFront:yourUIView)
gt0wga4j

gt0wga4j2#

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>>

相关问题