iOS用xib自定义view,修改不了frame的问题

转自:http://blog.sina.com.cn/s/blog_5971cdd00102wm5m.html


想要做一个图一所示的效果


由于我整体布局用的是tableview而不是collectionview,打算把四块商品展示弄成一个cell,

每一个商品展示用自定义View来写,for循环4次创建4个这样的View。如下图。



这个自定义View是用xib来做的,初始化代码如下:

HotProductView.m

-(id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        NSArray *nibs=[[NSBundle mainBundle]loadNibNamed:@"HotProductView" owner:nil options:nil];

        self=[nibs objectAtIndex:0];

        self.frame = frame;

    }

    return self;

}


Cell里创建这个自定义视图的代码如下:

HotProductView * proView = [[HotProductView alloc]initWithFrame:CGRectMake(10+(width+5)*0, 5+(height+5)*0, 150, 250)];

结果proView的宽高好像没有设置成功,总会比cell的contentview的高度还高。(绿为contentview,红为自定义view)


解决办法是 在-(void)drawRect:(CGRect)rect里面重新设置frame

HotProductView.m

@interface HotProductView ()

{

    CGRect myframe;

}

 

@end

@implementation HotProductView

-(id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        NSArray *nibs=[[NSBundle mainBundle]loadNibNamed:@"HotProductView" owner:nil options:nil];

        self=[nibs objectAtIndex:0];

        

        myframe = frame;

    }

    return self;

}

-(void)drawRect:(CGRect)rect

{

    self.frame=myframe;//关键点在这里

 

}

想要做一个图一所示的效果


由于我整体布局用的是tableview而不是collectionview,打算把四块商品展示弄成一个cell,

每一个商品展示用自定义View来写,for循环4次创建4个这样的View。如下图。



这个自定义View是用xib来做的,初始化代码如下:

HotProductView.m

-(id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        NSArray *nibs=[[NSBundle mainBundle]loadNibNamed:@"HotProductView" owner:nil options:nil];

        self=[nibs objectAtIndex:0];

        self.frame = frame;

    }

    return self;

}


Cell里创建这个自定义视图的代码如下:

HotProductView * proView = [[HotProductView alloc]initWithFrame:CGRectMake(10+(width+5)*0, 5+(height+5)*0, 150, 250)];

结果proView的宽高好像没有设置成功,总会比cell的contentview的高度还高。(绿为contentview,红为自定义view)


解决办法是 在-(void)drawRect:(CGRect)rect里面重新设置frame

HotProductView.m

@interface HotProductView ()

{

    CGRect myframe;

}

 

@end

@implementation HotProductView

-(id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        NSArray *nibs=[[NSBundle mainBundle]loadNibNamed:@"HotProductView" owner:nil options:nil];

        self=[nibs objectAtIndex:0];

        

        myframe = frame;

    }

    return self;

}

-(void)drawRect:(CGRect)rect

{

    self.frame=myframe;//关键点在这里

 

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值