在對程序橫屏適配的時候,發(fā)現(xiàn)MBProgressHUD會出現(xiàn)顯示方向異常
在豎屏狀態(tài)是正常顯示;
但在橫屏狀態(tài),方向還是豎屏狀態(tài),截圖如下:


在網(wǎng)上查找相關(guān)的資料,發(fā)現(xiàn)大部分都是提供在初始化的時候使用下列代碼
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
_hud = [[MBProgressHUD alloc] initWithWindow:window];
但是在實(shí)際MBProgressHUD開源類中,無法找到相關(guān)的位置添加上述代碼。同時也沒有提供相關(guān)位置信息;基本為無用資料。
在閱讀MBProgressHUD.m 的過程中,發(fā)現(xiàn)這個函數(shù):
- (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];
}
}
該方法主要內(nèi)容為:判斷當(dāng)前設(shè)備的方向,根據(jù)方向旋轉(zhuǎn)提示框。
通過斷點(diǎn)和控制臺輸出的方式,發(fā)現(xiàn)當(dāng)我的設(shè)備為橫屏狀態(tài),走進(jìn)了 if{}方法中,但是顯示效果卻是豎屏狀態(tài)。
郁悶的我猜想會不會已經(jīng)是正確的方向被擺歪了,于是我注釋了如下代碼塊
- (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];
}
}
在實(shí)際測試中發(fā)現(xiàn),無論是橫屏狀態(tài)還是豎屏狀態(tài)以及在相互切換的過程中,均正常顯示。
猜想:在創(chuàng)建提示框的時候,實(shí)際上已經(jīng)根據(jù)當(dāng)前的屏幕方向創(chuàng)建正確的提示框,但是調(diào)用了上述方法(之前可能非正確方向,加入該方法),才會出現(xiàn)這樣的 BUG。
畢業(yè)沒多久,如有幫助,希望點(diǎn)個贊,加個關(guān)注。
如果有描述的不對的地方,歡迎批評指正,共同進(jìn)步。
除非注明,均為原創(chuàng),轉(zhuǎn)載請注明出處,謝謝