Subview on top of window view in Swift

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!


For SWIFT 3 use this:

let window = UIApplication.shared.keyWindow!
window.addSubview(someView)

Tags:

Ios

Uiview

Swift