Tôi chỉ sử dụng Trung tâm thông báo:
Thêm một biến định hướng (sẽ giải thích ở cuối)
//Above viewdidload
var orientations:UIInterfaceOrientation = UIApplication.sharedApplication().statusBarOrientation
Thêm thông báo khi chế độ xem xuất hiện
override func viewDidAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "orientationChanged:", name: UIDeviceOrientationDidChangeNotification, object: nil)
}
Xóa thông báo khi chế độ xem biến mất
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceOrientationDidChangeNotification, object: nil)
}
Nhận hướng hiện tại khi thông báo được kích hoạt
func orientationChanged (notification: NSNotification) {
adjustViewsForOrientation(UIApplication.sharedApplication().statusBarOrientation)
}
Kiểm tra hướng (dọc / ngang) và xử lý các sự kiện
func adjustViewsForOrientation(orientation: UIInterfaceOrientation) {
if (orientation == UIInterfaceOrientation.Portrait || orientation == UIInterfaceOrientation.PortraitUpsideDown)
{
if(orientation != orientations) {
println("Portrait")
//Do Rotation stuff here
orientations = orientation
}
}
else if (orientation == UIInterfaceOrientation.LandscapeLeft || orientation == UIInterfaceOrientation.LandscapeRight)
{
if(orientation != orientations) {
println("Landscape")
//Do Rotation stuff here
orientations = orientation
}
}
}
Lý do tôi thêm biến định hướng là vì khi thử nghiệm trên một thiết bị vật lý, thông báo định hướng được gọi ở mọi chuyển động nhỏ trong thiết bị, chứ không chỉ khi nó xoay. Việc thêm lệnh var và if chỉ gọi mã nếu nó chuyển sang hướng ngược lại.
UIViewController. Xem phần có tiêu đề "Xử lý các