Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subview on top of window view in Swift

Tags:

ios

swift

uiview

I want to place a UIView over the entire screen (including the navigation bar). This view will be black with 0.3 opacity. I want to do this to darken out the screen content and push a view on top of this. I am using this code:

UIApplication.sharedApplication().keyWindow?.addSubview(darkView) 

This covers the whole screen as expected. However I now want to place another view on top of this dark view. Is there a way to do this? Everything I try just results in the view being under the dark view. Any pointers would be really appreciated! thanks

like image 964
Kex Avatar asked Jul 23 '16 09:07

Kex


People also ask

How do you check if a view contains a Subview?

If you need a quick way to get hold of a view inside a complicated view hierarchy, you're looking for viewWithTag() – give it the tag to find and a view to search from, and this method will search all subviews, and all sub-subviews, and so on, until it finds a view with the matching tag number.

How do I change the view frame in Swift?

You can update it by creating a new CGRect and assigning it to the property. CGRect(x:0, y:0, width:100, height:100) is fine. This initialiser is defined in the CGRect extension.


2 Answers

It's really simple.

You just add another view to window! And it will be there, on top of the first view you added. For example, this code adds a black view and a white view:

let window = UIApplication.sharedApplication().keyWindow! let v = UIView(frame: window.bounds) window.addSubview(v) v.backgroundColor = UIColor.blackColor() let v2 = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 50)) v2.backgroundColor = UIColor.whiteColor() window.addSubview(v2) 

You can also add the new view as a sub view of the first view you added:

let window = UIApplication.sharedApplication().keyWindow! let v = UIView(frame: window.bounds) window.addSubview(v) v.backgroundColor = UIColor.blackColor() let v2 = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 50)) v2.backgroundColor = UIColor.whiteColor() v.addSubview(v2) 

Swift 4

let window = UIApplication.shared.keyWindow! let v = UIView(frame: window.bounds) window.addSubview(v) v.backgroundColor = .black let v2 = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 50)) v2.backgroundColor = UIColor.white v.addSubview(v2) 

Simple!

like image 198
Sweeper Avatar answered Sep 28 '22 13:09

Sweeper


For SWIFT 3 use this:

let window = UIApplication.shared.keyWindow! window.addSubview(someView) 
like image 27
Mario Jaramillo Avatar answered Sep 28 '22 14:09

Mario Jaramillo