MBProgressHUD横屏适配

2017-02-09  本文已影响234人  丨不學無術丨

在对程序横屏适配的时候,发现MBProgressHUD会出现显示方向异常
在竖屏状态是正常显示;
但在横屏状态,方向还是竖屏状态,截图如下:

竖屏状态.png 横屏状态.png

在网上查找相关的资料,发现大部分都是提供在初始化的时候使用下列代码

UIWindow *window = [[UIApplication sharedApplication] keyWindow];  
_hud = [[MBProgressHUD alloc] initWithWindow:window];  

但是在实际MBProgressHUD开源类中,无法找到相关的位置添加上述代码。同时也没有提供相关位置信息;基本为无用资料。

在阅读MBProgressHUD.m 的过程中,发现这个函数:

    - (void)setTransformForCurrentOrientation:(BOOL)animated {  
      // Stay in sync with the superview
      if (self.superview) {
        self.bounds = self.superview.bounds;
        [self setNeedsDisplay];
    }   
      UIInterfaceOrientation orientation = [UIApplication   sharedApplication].statusBarOrientation;
      NSLog(@"%ld", orientation);
    CGFloat radians = 0;
    if (UIInterfaceOrientationIsLandscape(orientation)) {
          if (orientation ==   UIInterfaceOrientationLandscapeLeft) { radians = -  (CGFloat)M_PI_2; }
        else { radians = (CGFloat)M_PI_2; }
        // Window coordinates differ!
        self.bounds = CGRectMake(0, 0,   self.bounds.size.height, self.bounds.size.width);
    } else {
        if (orientation ==   UIInterfaceOrientationPortraitUpsideDown) { radians =   (CGFloat)M_PI; } 
        else { radians = 0; }
      }
      rotationTransform =   CGAffineTransformMakeRotation(radians);
    
      if (animated) {
        [UIView beginAnimations:nil context:nil];
      }
      [self setTransform:rotationTransform];
      if (animated) {
        [UIView commitAnimations];
      }
     }

该方法主要内容为:判断当前设备的方向,根据方向旋转提示框。
通过断点和控制台输出的方式,发现当我的设备为横屏状态,走进了 if{}方法中,但是显示效果却是竖屏状态。
郁闷的我猜想会不会已经是正确的方向被摆歪了,于是我注释了如下代码块

- (void)setTransformForCurrentOrientation:(BOOL)animated {  
// Stay in sync with the superview
  if (self.superview) {
    self.bounds = self.superview.bounds;
    [self setNeedsDisplay];
  }

  UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
  CGFloat radians = 0;
  /*if (UIInterfaceOrientationIsLandscape(orientation)) {
    if (orientation == UIInterfaceOrientationLandscapeLeft)   { radians = -(CGFloat)M_PI_2; }
    else { radians = (CGFloat)M_PI_2; }
    // Window coordinates differ!
    self.bounds = CGRectMake(0, 0,   self.bounds.size.height, self.bounds.size.width);
} else {
    if (orientation ==   UIInterfaceOrientationPortraitUpsideDown) { radians =   (CGFloat)M_PI; } 
    else { radians = 0; }
}*/
rotationTransform = CGAffineTransformMakeRotation(radians);
  if (animated) {
    [UIView beginAnimations:nil context:nil];
  }
  [self setTransform:rotationTransform];
  if (animated) {
    [UIView commitAnimations];
}
}

在实际测试中发现,无论是横屏状态还是竖屏状态以及在相互切换的过程中,均正常显示。

猜想:在创建提示框的时候,实际上已经根据当前的屏幕方向创建正确的提示框,但是调用了上述方法(之前可能非正确方向,加入该方法),才会出现这样的 BUG。

毕业没多久,如有帮助,希望点个赞,加个关注。
如果有描述的不对的地方,欢迎批评指正,共同进步。
除非注明,均为原创,转载请注明出处,谢谢

上一篇 下一篇

猜你喜欢

热点阅读