मैं केवल अधिसूचना केंद्र का उपयोग करता हूं:
एक अभिविन्यास चर जोड़ें (अंत में समझाएंगे)
//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")
//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
}
}
}
मेरे द्वारा अभिविन्यास चर जोड़ने का कारण यह है कि जब किसी भौतिक उपकरण पर परीक्षण किया जाता है, तो अभिविन्यास अधिसूचना डिवाइस में प्रत्येक छोटी चाल पर कॉल की जाती है, और न केवल जब यह घूमता है। संस्करण जोड़ना और यदि कथन केवल कोड को कॉल करते हैं यदि यह विपरीत अभिविन्यास में बदल जाता है।
UIViewController
। "हैंडलिंग घूर्णन देखें" शीर्षक वाला अनुभाग देखें। यह बताता है कि आपको क्या करना चाहिए।