如何在 Swift 中向后发送 UIView 元素



所以我有一个按钮,我已经在main中添加了它。情节提要,以及视图的主背景,然后在 viewController.swift 文件中,我创建了一个 UIView 矩形形状,我想坐在该按钮后面(作为它的背景)。

问题是,当我添加矩形UIView时,它总是将其添加到按钮前面。所以我在网上研究了一下,找到了sendSubviewToBack代码。我已经添加了它,但它将其一直发送到视图的主 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)
}

来自苹果文档:

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

您可以使用以下命令将酒吧放在前面:

view.bringSubviewToFront(nextBar) 

您可以使用以下命令将视图发送到栏的背面:

nextBar.view.sendSubviewToBack(myView)

对于 Swift 4:

self.view.sendSubviewToBack(toBack: myView)

在 Swift 4.2 中,可以使用以下命令完成:

self.sendSubviewToBack(view: viewSentToBack)

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

最新更新