How to send a UIView element backwards in Swift

20,276

Solution 1

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)

Solution 2

For Swift 4:

self.view.sendSubviewToBack(toBack: myView)

Solution 3

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.

Share:
20,276
Nick89
Author by

Nick89

Great passion for digital technology and innovation. I have some experience in HTML and CSS. Learning to code Swift with no prior experience in mobile app coding. Hobbies include Snowboarding, football, and running my small business in Photography and Filming.

Updated on April 12, 2021

Comments

  • Nick89
    Nick89 about 3 years

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