基本上,我的UIViewController
里有一个UIView
。我希望用户能够按下一个按钮,然后UIView
从我的UIViewController
移动到我的应用程序的窗口,以便UIView
将首先UIViewControllers
。我唯一能想到做的是
class ViewController: UIViewController {
var window = UIApplication.shared.keyWindow!
var view = UIView()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(view)
}
func tappedAction() {
window.bringSubview(toFront: view)
}
}
但这没有用。我怎样才能做到这一点?
您不能只是将UIViewController
中的子视图放在UIWindow
的前面。
您需要:
- 从
UIViewController
上取下UIView
。 - 将
UIView
添加到主UIWindow
。
我选择以这种方式执行此操作:
import UIKit
class ViewController: UIViewController {
var customView: UIView!
// Load the main view of the UIViewController.
override func loadView() {
view = UIView()
}
override func viewDidLoad() {
super.viewDidLoad()
// Load the custom view that we will be transferring.
self.customView = UIView(frame: .init(x: 100, y: 250, width: 250, height: 250))
self.customView.backgroundColor = .red
view.addSubview(customView)
// Transfer the view. Call this method in your trigger function.
transfer(self.customView)
}
func transfer(_ view: UIView) {
// Remove the view from the UIViewController.
view.removeFromSuperview()
// Add the view to the UIWindow.
UIApplication.shared.windows.first!.addSubview(view)
}
}
您必须在var view = UIView()
处设置视图的帧
然后你应该添加到窗口window.addSubview(view)
如果您的视图被添加到窗口中,那么window.bringSubview(toFront: view)
将起作用,否则它将无法工作。
如果您的视图被添加到窗口上,那么您可以使用这样的bringSubview(toFront:)
: 例:
let window = UIApplication.shared.keyWindow!
let view1 = UIView(frame: CGRect(x: window.frame.origin.x, y: window.frame.origin.y, width: window.frame.width, height: window.frame.height))
window.addSubview(view1);
view1.backgroundColor = UIColor.black
let view2 = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 50))
view2.backgroundColor = UIColor.white
window.addSubview(view2)
UIApplication.shared.keyWindow!.bringSubview(toFront: view1)
所以你需要在窗口中添加你的视图:
window.addSubview(view)