简体   繁体   中英

Using a notification with which I retrieve the orientation change before it occurs

Because UIDeviceOrientationDidChangeNotification is to late for me I thought I use UIApplicationWillChangeStatusBarOrientationNotification .

This is how I subscribe:

observer = NSNotificationCenter.DefaultCenter.AddObserver ((NSString)UIApplication.WillChangeStatusBarOrientationNotification, UpdateIntrinsicConstraints);

Now I want to extract the orientation

public void UpdateIntrinsicConstraints(NSNotification notification){
    // Cannot convert type 'Foundation.NSObject' to 'UIKit.UIInterfaceOrientation'
    switch ((UIInterfaceOrientation)notification.UserInfo.ValueForKey(UIApplication.StatusBarOrientationUserInfoKey))
    {
        case UIInterfaceOrientation.LandscapeLeft:
            // ...
            break;
        default:
            break;
    }
}

, but I can't convert from NSObject to UIInterfaceOrientation .

Is UIApplicationWillChangeStatusBarOrientationNotification right for me and how can I extract the orientation to which the interface rotates (like willRotateToInterfaceOrientation )?

Actually what you get from

notification.UserInfo.ValueForKey(UIApplication.StatusBarOrientationUserInfoKey)

is an NSNumber. So you have to get that NSNumber's value as Int. Then you can cast that int to UIInterfaceOrientation. Same thing in code:

short shortValue = ((NSNumber)notification.UserInfo.ValueForKey(UIApplication.StatusBarOrientationUserInfoKey)).Int16Value;
UIInterfaceOrientation orientation = ((UIInterfaceOrientation)shortValue);
switch (orientation)
 {
     case UIInterfaceOrientation.LandscapeLeft:
         // ...
         break;
      default:
         break;
 }

Or if you prefer the same in one line:

switch ((UIInterfaceOrientation)((NSNumber)notification.UserInfo.ValueForKey(UIApplication.StatusBarOrientationUserInfoKey)).Int16Value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM