Swift 5 / iOS 13-导航控制器中嵌入了奇怪的视图位置行为

问题描述

希望一切都很好。直接解决问题:

环境:11.6版/ Swift 5

UINavigationController中嵌入了一个基本的视图控制器(TestViewController)。 假设此TestViewController具有一个按钮,该按钮可通过点击向上移动self.view。 将视图向上移动,然后离开应用程序(使其保持不活动状态或后台运行)并再次返回(再次处于活动状态), 所移动的视图将返回到y位置0,这意味着视图框架将返回到CGRect(0,0,yourViewWidth,yourViewHeight)。

repro仅是代码,不需要Storyboard。

首先是一个SceneDelegate,它将在启动时初始化导航控制器,并在应用程序激活时在控制台中打印呼叫消息。 我为什么认为UINavigationController会发生这种情况,是因为它不只是UIViewController。您可以通过对委托中的根视图控制器的初始化行添加注释/取消注释来对其进行测试:

class SceneDelegate: UIResponder,UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene,willConnectTo session: UIScenesession,options connectionoptions: UIScene.Connectionoptions) {
        guard let windowScene = (scene as? UIWindowScene) else { return }
        let window = UIWindow(windowScene: windowScene)
        window.makeKeyAndVisible()
        self.window = window
        window.rootViewController = UINavigationController(rootViewController: TestViewController())
/// Please try with normal view controller as below
//        let controller = TestViewController()
//        window.rootViewController = controller
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        print("sceneDidBecomeActive")
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    }
}

第二部分和最后一部分更加简单。看看:

class TestViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton(frame: CGRect(x: view.frame.width/2,y: view.frame.height/2,width: 100,height: 100))
        button.setTitle("click",for: .normal)
        button.addTarget(self,action: #selector(buttonTapped),for: .touchUpInside)
        button.backgroundColor = .green
        view.addSubview(button)
    }
    
    @objc func buttonTapped() {
        view.frame.origin.y -= 200
    }
}

gifs。

enter image description here

enter image description here

有人能弄清楚为什么会这样吗?可能不是由于UINavigationController所致,所以请教我!可能是错误或意图。完全不知道任何建议将不胜感激!在此先感谢:)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)