遇到過好多次使用自定義view,修改frame無效問題, 之前都是放棄xib,直接手寫,發現手寫簡單的還行,復雜的UI就坑逼了。所以還是需要用到可視化編輯的xib。
整理一下,自己備忘也供iOS開發的朋友參考:
一般我們會直接這樣寫:
XPGovRecUnitView *recUnitView = [[[NSBundle mainBundle] loadNibNamed:@"XPGovRecUnitView" owner:self options:nil] firstObject];
recUnitView.tag = 10000+i;
recUnitView.delegate = self;
recUnitView.frame = CGRectMake(i*89, 0, 89, 139);
這是我一個項目中的代碼,但是這樣出現了一個問題就是iPhone 6,6Plus以上的正常, iPhone5s屏幕尺寸的就顯示不正常了。
使用
UIView *recUnitView = [[UIView alloc] initWithFrame:CGRectMake(i*89, 0, 89, 139)];
調試後發現,使用alloc的方式iPhone5也是正常的。但是這樣就要手寫代碼,往這個UIView 添加控件
解決方案:
1. 先把 XPGovRecUnitView.xib這個xib文件的屬性設置一下
在右側屬性欄中,
找到Interface Builder Document , 把Use Auto layout的勾去掉
找到Simulated Metrics , 把Size 設置成None, 沒有None就是Freeform
2.修改XPGovRecUnitView.m代碼
#import "XPGovRecUnitView.h"
@interface XPGovRecUnitView ()
{
CGRect tempframe;
}
@end
@implementation XPGovRecUnitView
-(id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSArray *nibs=[[NSBundle mainBundle]loadNibNamed:@"XPGovRecUnitView" owner:nil options:nil];
self=[nibs objectAtIndex:0];
tempframe = frame;
[self initSubViews];
}
return self;
}
-(void)drawRect:(CGRect)rect
{
self.frame = tempframe;
}
@end
3.使用時代碼
XPGovRecUnitView *recUnitView = [[XPGovRecUnitView alloc] initWithFrame:CGRectMake(i*89, 0, 89, 139)];
recUnitView.tag = 10000+i;
recUnitView.delegate = self;
這樣就正常了。