How to send a UIView element backwards in Swift

23.1k Views Asked by At

So I have a Button which i have added in main.Storyboard, along with a main background for the View, and then in the viewController.swift file, I have created a UIView rectangle shape which I want to sit behind that button (as a background for it).

The problem is, when I added the rectangle UIView it always added it in front of the button. So I researched online and found the sendSubviewToBack code. I have added this in, but it sends it all the way behind the main UIImage background of the view.

Is there a way i can just send this UIView behind the button but in front of the UIImage background?

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

There are 3 best solutions below

1
On BEST ANSWER

From apple documentation:

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

You can bring your bar to the front using:

view.bringSubviewToFront(nextBar) 

Your send your view to the back of the bar using:

nextBar.view.sendSubviewToBack(myView)
1
On

For Swift 4:

self.view.sendSubviewToBack(toBack: myView)
0
On

In Swift 4.2 it can be done with:

self.sendSubviewToBack(view: viewSentToBack)

An object in the view that is linked by an IBOutlet can be sent to back using the above function.