我只是使用通知中心:
添加一个方向变量(将在最后解释)
//Above viewdidload
var orientations:UIInterfaceOrientation = UIApplication.sharedApplication().statusBarOrientation
视图出现时添加通知
override func viewDidAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "orientationChanged:", name: UIDeviceOrientationDidChangeNotification, object: nil)
}
当视图消失时移除通知
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceOrientationDidChangeNotification, object: nil)
}
当通知被触发时,获取当前方向。
func orientationChanged (notification: NSNotification) {
adjustViewsForOrientation(UIApplication.sharedApplication().statusBarOrientation)
}
检测屏幕方向(纵向或横向),并处理相关事件
func adjustViewsForOrientation(orientation: UIInterfaceOrientation) {
if (orientation == UIInterfaceOrientation.Portrait || orientation == UIInterfaceOrientation.PortraitUpsideDown)
{
if(orientation != orientations) {
println("Portrait")
orientations = orientation
}
}
else if (orientation == UIInterfaceOrientation.LandscapeLeft || orientation == UIInterfaceOrientation.LandscapeRight)
{
if(orientation != orientations) {
println("Landscape")
orientations = orientation
}
}
}
我添加方向变量的原因是因为在物理设备上进行测试时,每次设备的微小移动都会触发方向通知,而不仅仅是旋转时才会触发。添加变量和if语句只会在它切换到相反方向时调用代码。
UIViewController
的文档。查看标题为“处理视图旋转”的部分。它会解释你应该做什么。 - rmaddy