将 UIView 从 ViewController 移动到 Window

问题描述 投票:0回答:3

基本上,我的

UIView
里有一个
UIViewController
。我希望用户能够按下一个按钮,然后
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)
    }
}

但这没有用。我怎样才能做到这一点?

ios swift uiview uiviewcontroller window
3个回答
1
投票

您不能只将

UIViewController
中的子视图带到
UIWindow
的前面。

你需要:

  1. UIView
    中删除
    UIViewController
  2. 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)
    }
}

0
投票

您必须在

var view = UIView()

处设置框架

然后你应该添加到窗口

window.addSubview(view)


0
投票

如果您的视图添加到窗口上,那么

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)
© www.soinside.com 2019 - 2024. All rights reserved.