iOS 使用xib定义一个View,修改frame无效问题解决

遇到过好多次使用自定义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;

  

这样就正常了。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值