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

来源:互联网 发布:软件设计师成绩查询 编辑:程序博客网 时间:2024/05/17 23:31

转自: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 = [superinitWithFrame:frame];

    if (self) {

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

        self=[nibsobjectAtIndex:0];

        self.frame = frame;

    }

    return self;

}


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

HotProductView * proView = [[HotProductViewalloc]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 = [superinitWithFrame:frame];

    if (self) {

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

        self=[nibsobjectAtIndex: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 = [superinitWithFrame:frame];

    if (self) {

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

        self=[nibsobjectAtIndex:0];

        self.frame = frame;

    }

    return self;

}


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

HotProductView * proView = [[HotProductViewalloc]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 = [superinitWithFrame:frame];

    if (self) {

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

        self=[nibsobjectAtIndex:0];

        

        myframe = frame;

    }

    return self;

}

-(void)drawRect:(CGRect)rect

{

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

 

}


0 0
原创粉丝点击