xib 文件更改后视图方向错误
Posted
技术标签:
【中文标题】xib 文件更改后视图方向错误【英文标题】:Wrong orientation of view after xib file changed 【发布时间】:2014-09-19 05:58:40 【问题描述】:在我的设计中,有一个按钮可以更改 xib 文件。 google了一千次后,我找到了如下所示的解决方案:
- (IBAction)changeButtonDidPress:(id)sender
dispatch_async(dispatch_get_main_queue(), ^
if (self.xibChanged)
NSArray *nibObjs = [[NSBundle mainBundle] loadNibNamed:@"MyViewController" owner:self options:nil];
UIView *aView = [nibObjs objectAtIndex:0];
self.view = aView;
self.xibChanged = NO;
else
NSArray *nibObjs = [[NSBundle mainBundle] loadNibNamed:@"CustomViewController" owner:self options:nil];
UIView *aView = [nibObjs objectAtIndex:0];
self.view = aView;
self.xibChanged = YES;
);
但是,有一个问题:更改xib文件后视图的方向是错误的(总是纵向,不管我如何设置xib文件)! ps:我也试过了: 1) Change view in one XIB,工作得很好,但这意味着我需要创建一个新的控制器,这是我从未想要的! 2) Single UIViewcontroller, how to switch among multiple xibs?,根本没用,新视图中一些按钮丢失了! 所以,我发布了这个问题,有人遇到过类似的问题吗?有什么好主意吗?谢谢!
【问题讨论】:
【参考方案1】:嗯,经过一千次重试,我才找到了一个解决方法:rotate your new view that has wrong orientation
。
一开始,请务必xibs使用autosizing,否则你应该多加努力!
然后将此方法添加到您的视图控制器:
- (void)rotateUIView:(UIView *)aView toInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
// Get data of rotating view
CGRect bounds = [[UIScreen mainScreen] bounds];
CGFloat angle = 0.0f, width = 0.0f, height = 0.0f;
switch (interfaceOrientation)
case UIInterfaceOrientationPortraitUpsideDown:
angle = M_PI;
width = bounds.size.width;
height = bounds.size.height;
break;
case UIInterfaceOrientationLandscapeLeft:
angle = -M_PI_2;
height = bounds.size.width;
width = bounds.size.height;
break;
case UIInterfaceOrientationLandscapeRight:
angle = M_PI_2;
height = bounds.size.width;
width = bounds.size.height;
break;
case UIInterfaceOrientationPortrait:
default:
return;
// Rotate the view
[aView setBounds:CGRectMake(0, 0, width, height)];
[aView setTransform:CGAffineTransformConcat(aView.transform, CGAffineTransformMakeRotation(angle))];
修改xib文件后调用该方法,如下:
[self rotateUIView:self.view toInterfaceOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
那么视图的方向就可以了!希望这也能解决你的问题!
【讨论】:
以上是关于xib 文件更改后视图方向错误的主要内容,如果未能解决你的问题,请参考以下文章
Interface Builder 布局 UIViewController xib 用于更改顶部栏高度的方向
从 xib 添加自定义视图作为子视图时,UITableViewCell 的高度错误