如何解决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。
有人能弄清楚为什么会这样吗?可能不是由于UINavigationController所致,所以请教我!可能是错误或意图。完全不知道任何建议将不胜感激!在此先感谢:)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。