Programing

iPad의 현재 방향을 얻으시겠습니까?

crosscheck 2020. 11. 26. 07:52
반응형

iPad의 현재 방향을 얻으시겠습니까?


주어진 이벤트 핸들러 ( "shouldAutorotateToInterfaceOrientation"메소드가 아님)에서 현재 iPad 방향을 어떻게 감지합니까? 가로보기에서 (키보드가 나타날 때) 애니메이션을 적용해야하는 텍스트 필드가 있지만 세로보기에서는 아니고 애니메이션이 필요한지 확인하기 위해 어떤 방향인지 알고 싶습니다.


오리엔테이션 정보는 일관 적이 지 않으며 몇 가지 접근 방식이 있습니다. 뷰 컨트롤러에서 interfaceOrientation속성을 사용할 수 있습니다 . 다른 곳에서 전화를 걸 수 있습니다.

[[UIDevice currentDevice] orientation]

또는 방향 변경 알림 수신을 요청할 수 있습니다.

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];

어떤 사람들은 상태 표시 줄 방향도 확인하고 싶어합니다.

[UIApplication sharedApplication].statusBarOrientation

나는 생각한다

[[UIDevice currentDevice] orientation];

정말 신뢰할 수 없습니다. 때로는 작동하지만 때로는 작동하지 않습니다 ... 내 앱에서

[[UIApplication sharedApplication]statusBarOrientation]; 

그리고 그것은 훌륭하게 작동합니다!


다음 중 하나 :

  • interfaceOrientation활성 뷰 컨트롤러 속성을 확인하십시오 .
  • [UIApplication sharedApplication].statusBarOrientation.
  • [UIDevice currentDevice].orientation. (으로 전화해야 할 수도 있습니다 -beginGeneratingDeviceOrientationNotifications.)

FaceUp 방향 문제를 해결하는 트릭을 찾았습니다 !!!

앱 실행이 시작될 때까지 방향 확인을 연기 한 다음 변수,보기 크기 등을 설정하세요 !!!

//CODE

- (void)viewDidLoad {

  [super viewDidLoad];

  //DELAY
  [NSTimer scheduledTimerWithTimeInterval:0.5 
                     target:self 
                     selector:@selector(delayedCheck) 
                     userInfo:nil 
                     repeats:NO];

}


-(void)delayedCheck{

  //DETERMINE ORIENTATION
  if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait ){
      FACING = @"PU";
  }
  if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown ){
      FACING = @"PD";
  }
  if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeLeft ){
      FACING = @"LL";
  }
  if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeRight ){
      FACING = @"LR";
  } 
  //DETERMINE ORIENTATION

  //START
  [self setStuff];
  //START

}


-(void)setStuff{

  if( FACING == @"PU" ){
          //logic for Portrait
  }
  else
  if( FACING == @"PD" ){
          //logic for PortraitUpsideDown
  }
  else{ 
  if( FACING == @"LL"){
          //logic for LandscapeLeft
  }
  else
  if( FACING == @"LR" ){
          //logic for LandscapeRight
  }

}

//CODE

'setStuff'함수에 Subviews, 위치 요소 등을 추가 할 수 있습니다. 처음에는 방향에 따라 달라지는 모든 것 !!!

:디

-크리스 앨 린슨


다음 두 가지 방법으로이를 달성 할 수 있습니다.

1- 다음 방법을 사용합니다.

** -(void)viewDidLoad방법에 다음 줄을 입력하십시오 .

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceRotated:) name:UIDeviceOrientationDidChangeNotification object:nil];

그런 다음이 메서드를 클래스 안에 넣으십시오.

-(void)deviceRotated:(NSNotification*)notification
{

   UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    if(orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight)
    {
        //Do your textField animation here
    }
}

위의 방법은 장치가 회전 할 때 방향을 확인합니다.

2- 두 번째 방법은 내부에 다음 알림을 삽입하는 것입니다. -(void)viewDidLoad

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkRotation:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];

그런 다음 클래스 안에 다음 메소드를 넣으십시오.

-(void)checkRotation:(NSNotification*)notification
{
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if(orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight)
    {
         //Do your textField animation here
    }
}

The above method will check the orientation of the status bar of the ipad or iPhone and according to it you make do your animation in the required orientation.


For determining landscape vs portrait, there is a built-in function:

UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
BOOL inLandscape = UIDeviceOrientationIsLandscape(orientation);

[UIApplication sharedApplication].statusBarOrientation returns portrait when it's landscape, and landscape when it's portrait at launch, in iPad


I don't know why, but every time my app starts, the first 4 are right, but subsequently I get the opposite orientation. I use a static variable to count this, then have a BOOL to flip how I manually send this to subviews.

So while I'm not adding a new stand-alone answer, I'm saying use the above and keep this in mind. Note: I'm receiving the status bar orientation, as it's the only thing that gets called when the app starts and is "right enough" to help me move stuff.

The main problem with using this is the views being lazily loaded. Be sure to call the view property of your contained and subviews "Before" you set their positions in response to their orientation. Thank Apple for not crashing when we set variables that don't exist, forcing us to remember they break OO and force us to do it, too... gah, such an elegant system yet so broken! Seriously, I love Native, but it's just not good, encourages poor OO design. Not our fault, just reminding that your resize function might be working, but Apple's Way requires you load the view by use, not by creating and initializing it


In your view controller, get the read-only value of self.interfaceOrientation (the current orientation of the interface).


I've tried many of the above methods, but nothing seemed to work 100% for me.

My solution was to make an iVar called orientation of type UIInterfaceOrientation in the Root View Controller.

- (void)viewDidLoad {

    [super viewDidLoad];
    orientation = self.interfaceOrientation; // this is accurate in iOS 6 at this point but not iOS 5; iOS 5 always returns portrait on app launch through viewDidLoad and viewWillAppear no matter which technique you use.
}


- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
    return YES;
}

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{

    orientation =  toInterfaceOrientation;

}

Then, any place where you need to check the orientation you can do something like this:

 if(UIInterfaceOrientationIsPortrait(orientation)){
    // portrait
  }else{
   // landscape
  }

There may still be a better way, but this seems to work 98% of the time (iOS5 notwithstanding) and isn't too hard. Note that iOS5 always launches iPad in portrait view, then sends a device the willRotateTo- and didRotateFromInterfaceOrientation: messages, so the value will still be inaccurate briefly.


[UIDevice currentDevice].orientation works great.

BUT!!! ... the trick is to add it to - (void)viewWillAppear:(BOOL)animated

exp:

(void)viewWillAppear:(BOOL)animated{
   ...
   BOOL isLandscape = UIInterfaceOrientationIsLandscape(self.interfaceOrientation);
   ...
}

If you call it at - (void)viewDidLoad, it does not work reliable, especially if you use multiple threads (main UI thread, background thread to access massive external data, ...).


Comments: 1) Even if your app sets default orientation portrait, user can lock it at landscape. Thus setting the default is not really a solution to work around it. 2) There are other tasks like hiding the navigation bar, to be placed at viewWillAppear to make it work and at the same time prevent flickering. Same applies to other views like UITableView willDisplayCell -> use it to set cell.selected and cell.accessoryType.

참고URL : https://stackoverflow.com/questions/2738734/get-current-orientation-of-ipad

반응형