我想在整个屏幕上放置一个UIView(包括导航栏)。该视图将为黑色,具有0.3不透明度。我想这样做是为了使屏幕内容变暗并在此基础上推送视图。我正在使用此代码:
UIApplication.sharedApplication().keyWindow?.addSubview(darkView)
这涵盖了预期的整个屏幕。但是我现在想在这个黑暗的视图之上放置另一个视图。有没有办法做到这一点?我尝试的一切只会导致视图处于黑暗视野之下。任何指针都会非常感激!感谢
答案 0 :(得分:60)
真的简单。
您只需向window
添加另一个视图即可!它会在你添加的第一个视图之上。例如,此代码添加了黑色视图和白色视图:
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)
您还可以将新视图添加为您添加的第一个视图的子视图:
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 = UIColor.black
let v2 = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 50))
v2.backgroundColor = UIColor.white
v.addSubview(v2)
简单!
答案 1 :(得分:17)
对于SWIFT 3,请使用:
let window = UIApplication.shared.keyWindow!
window.addSubview(someView)
答案 2 :(得分:3)
Swift 4 , 将 UIViewController 作为子视图添加到 UIWindow
此代码用于添加视图控制器作为子视图,用简单的动画覆盖整个窗口。
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var customReviewPopup = ReviewPopupViewController.init(nibName: "ReviewPopupViewController", bundle: Bundle.main)
self.appDelegate.window?.addSubview((customReviewPopup.view)!)
self.customReviewPopup.view.frame = (self.appDelegate.window?.bounds)!
self.customReviewPopup.view.alpha = 0
self.customReviewPopup.view.isHidden = true
UIView.animate(withDuration: 0.3, delay: 0, options: .transitionCrossDissolve, animations: {
self.customReviewPopup.view.isHidden = false
self.customReviewPopup.view.alpha = 1
}, completion: nil)
答案 3 :(得分:3)
Swift 5:
let window = UIApplication.shared.windows.last!
let viewToShow = UIView(frame: CGRect(x: 0, y: 0, width: window.frame.size.width, height: 40.0))
viewToShow.backgroundColor = UIColor.white
window.addSubview(viewToShow)