突然发现用之前的方法添加xib自定义的view,显示上有问题,如下图,添加的view宽度上存在问题。
1、这是创建的xib自定义的view
2、关联脚本
3、在UIViewController里加载nib,添加view
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
MyView *myView = [[[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil] lastObject];
[myView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
[self.view addSubview:myView];
}
这样写在xcode旧版本创建的脚本写是没有问题的,在新版本就会出现如上所述问题。
解决方法一
在UIViewController.xib中,把view->Drawing->Autoresize Subviews勾去掉就没问题了。
如果视图的autoresizesSubviews属性被设置为 NO,则该视图的直接子视图的所有自动尺寸调整行为将被忽略。类似地,如果一个子视图的自动尺寸调整掩码被设置为 UIViewAutoresizingNone,则该子视图的尺寸将不会被调整,因而其直接子视图的尺寸也不会被调整。
解决方法二
还可以在MyView里写
#import "MyView.h"
@interface MyView()
@property (assign, nonatomic) CGRect viewframe;
@end
@implementation MyView
//对frame重新赋值
- (void)drawRect:(CGRect)rect {
// Drawing code
self.frame = self.viewframe;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil];
if (arrayOfViews.count < 1)
{
return nil;
}
self = [arrayOfViews objectAtIndex:0];
self.viewframe = frame;
}
return self;
}
@end
在 UIViewController里初始化添加view
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
MyView *myView = [[MyView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
[self.view addSubview:myView];
}