Thursday, October 18, 2012

More orientation in iOS with MonoTouch

I ran into some interesting orientation distinctions with MonoTouch development. Luckily the good folks at Xamarin were very helpful on their forums.

 Regarding orientation, this is what I learned from Adam Kemp:

There are two kinds of orientation: device orientation UIDeviceOrientation and interface orientation UIInterfaceOrientation. Interface orientation tells you whether it's portrait, portrait upside down, landscape left, or landscape right. Device orientation has more spatial orientations like face up or face down (i.e., how is the user holding the device, rather than what does the screen look like). Device orientation is much more prone to changes even when the interface doesn't change at all (and sometimes the device doesn't know at all, hence the "unknown").

UIDevice.CurrentDevice.Orientation gives you the device orientation.

To get interface orientation you use UIApplication.SharedApplication.StatusBarOrientation.

You can also observe changes to the orientation by adding an observer like this:

   _interfaceNotificationHandle = 
         NSNotificationCenter.DefaultCenter.AddObserver(
            UIApplication.DidChangeStatusBarOrientationNotification, 
            HandleInterfaceOrientationDidChangeNotification); 


And don't forget to unregister (in this case I do it in Dispose(), but for a view you might want to register when the view is added to a window and unregister when it's removed):


public void Dispose() 
{ 
    if (!_disposed) 
    { 
        if (_interfaceNotificationHandle != null) 
        { 
            NSNotificationCenter.DefaultCenter
                .RemoveObserver(_interfaceNotificationHandle); 

            _interfaceNotificationHandle = null; 
        }
        
        _disposed = true; 
         
    } 
}

0 comments:

Post a Comment