Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a UIView element backwards in Swift

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)

}
like image 807
Nick89 Avatar asked Jun 10 '15 23:06

Nick89


2 Answers

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)
like image 72
Icaro Avatar answered Nov 19 '22 11:11

Icaro


For Swift 4:

self.view.sendSubviewToBack(toBack: myView)
like image 9
xhinoda Avatar answered Nov 19 '22 09:11

xhinoda