如何以编程方式将视图设置为 front/back?

How to programmatically set view to the front/back?

我正在开发一个使用 UIViews 作为文本背景的应用程序。我已将视图放在 storyboard 中的文本后面,但出于某种原因,有些视图似乎仍位于文本前面。有没有办法以编程方式将这些视图发送到后面?这是我正在谈论的内容的屏幕截图

sendSubviewToBack API 就是你想要的这个任务。

Moves the specified subview so that it appears behind its siblings.

This method moves the specified view to the beginning of the array of views in the subviews property.

UIView class 参考

下面是 Swift 语言中的代码片段,说明如何调用此 API:

Swift

yourSuperview.sendSubviewToBack(yourSubview)

您可以使用这两个中的一个:

- (void)bringSubviewToFront:(UIView *)view;
- (void)sendSubviewToBack:(UIView *)view;

Objective-C 用法

view.sendSubviewToBack(subview)view.bringSubviewToFront(subview)

SWIFT 4.2 用法

view.sendSubview(toBack: subview)
view.bringSubview(toFront: subview)
  • bringSubviewToFront: 移动指定的子视图,使其显示在其兄弟视图之上。
  • 发送子视图返回: 移动指定的子视图,使其出现在其兄弟视图的后面。

https://developer.apple.com/reference/uikit/uiview?language=objc

Swift 5

yourSuperview.sendSubviewToBack(yourSubview)

 yourSuperview.bringSubviewToFront(yourSubview)