我正在写一个绘图应用程序-景观位置的内容在肖像的坐标系统。我的viewController检测方向改变的最简单方法是什么?
编辑我知道2014年9月有一个类似的问题,但解决方案似乎特定于代码-有人能澄清什么最简单的方法来检测旋转可能是?(代码解释也不错)
我尝试了实现,但一直在NSNotificationCenter上得到"预期声明"错误
(为了清晰起见,这里是参考的解决方案:)
在AppDelegate.swift的"didFinishLaunchingWithOptions"里面:
`NSNotificationCenter.defaultCenter().addObserver(self, selector: "rotated", name: UIDeviceOrientationDidChangeNotification, object: nil)`
在AppDelegate类中:
func rotated()
{
if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation))
{
println("landscape")
}
if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation))
{
println("Portrait")
}
}
这是我发现的最简单的方式来对旋转作出反应,这应该是一个容易实现的大多数-被覆盖的函数被称为"任何时候视图的框架改变,它的子视图因此被重新布局"(来源:斯坦福CS193p幻灯片)
viewController中的(要旋转的视图):
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
// code to handle rotation details
}
这个方法有一个问题。如果你在主视图上添加了很多子视图,这个函数会被调用很多次。
我认为最好的方法是:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
// Your Processing
}
此外,您有参数来帮助您处理