在Swift窗口视图顶部的子视图

问题描述:

我想在整个屏幕(包括导航栏)上放置一个UIView.该视图将是黑色的,具有0.3的不透明度.我想这样做是为了使屏幕内容变暗,并在此之上推一个视图.我正在使用此代码:

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

这真的很简单.

您只需向window添加另一个视图!它会在您添加的第一个视图之上.例如,此代码添加了一个黑色视图和一个白色视图:

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)

快捷键4

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

简单!