如何在Swift中将UIView元素发送到后面

21

我在 main.Storyboard 中添加了一个按钮和一个视图的主背景,然后在 viewController.swift 文件中创建了一个矩形 UIView 形状,我希望它作为按钮的背景。

问题是,当我添加矩形 UIView 时,它总是被放在按钮的前面。所以我在网上查找资料,找到了 sendSubviewToBack 代码。我已经将其添加进去了,但它把这个 UIView 发送到了视图的主 UIImage 背景的后面。

有没有办法仅将此 UIView 发送到按钮的后面,但在 UIImage 背景的前面呢?

func nextBarDisplayed() {

    let theHeight = self.view.frame.height
    nextBar.backgroundColor = UIColor(red: 7/255, green: 152/255, blue: 253/255, alpha: 0.5)
    nextBar.frame = CGRect(x: 0, y: theHeight - 50, width: self.view.frame.width, height: 50)
    self.view.insertSubview(nextBar, aboveSubview: myBackgroundView)

}
3个回答

52

来自苹果文档:

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

你可以使用以下代码将你的导航栏置于最上层:

view.bringSubviewToFront(nextBar) 

您可以使用以下方法将您的视图发送到栏的后面:

nextBar.view.sendSubviewToBack(myView)

1
好消息!请不要忘记向人们说明错误和正确的方法,以便他们能够理解问题。祝你完成应用程序顺利! - Icaro

9

针对Swift 4:

self.view.sendSubviewToBack(toBack: myView)

7
Swift 4.2 已经重新更名为 sendSubviewToBack - Claus Jørgensen

1
在Swift 4.2中,可以使用以下代码实现:
self.sendSubviewToBack(view: viewSentToBack)

在视图中由IBOutlet链接的对象可以使用上述函数发送到后面。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接