使用Auto Layout导致调用addSubView时出现的问题

来源:互联网 发布:康辉旅游网站源码 编辑:程序博客网 时间:2024/05/17 05:55

今天在一个自定义的UITableViewCell中添加一个UIView的时候发现怎么都不显示添加的UIView,在stackoverflow上搜了一下才想起来自己把viewController的auto layout打开了, stackoverflow上的回答iOS Auto Layout - get frame size width ,一楼大概讲的就是auto layout加载的方式并且只有在auto layout之后才能获取self的frame,二楼也给出了解决方法在viewDidLayoutSubViews中写用到frame的代码或者干脆用最省事的方法关掉auto layout。

这里只是一段测试的代码,添加subview时应该写在layoutsubviews方法里面。

一开始找错了答案重写了initWithCoder发现可以显示添加的View但是返回的frame值有点问题,至于为什么就不太清楚了。

- (void)awakeFromNib {    UIView *view = [[UIView alloc] init];    view.backgroundColor = [UIColor blackColor];    CGFloat x = 0;    CGFloat h = 10;    CGFloat w =  self.frame.size.width;    CGFloat y = self.frame.size.height - h;    view.frame = CGRectMake(x, y, w, h);    [self.contentView addSubview:view];    NSLog(@"awakeFromNib  H:%f,W:%f",self.frame.size.height,self.frame.size.width);}-(void)setFrame:(CGRect)frame {    [super setFrame:frame];    NSLog(@"setFrame  H:%f,W:%f",frame.size.height,frame.size.width);}- (instancetype)initWithFrame:(CGRect)frame {    NSLog(@"initWithFrame  %f---%f",frame.size.height,frame.size.width);    return [super initWithFrame:frame];}- (id)initWithCoder:(NSCoder *)aDecoder {    NSLog(@"initWithCoder  H:%f,W:%f",self.frame.size.height,self.frame.size.width);  return [self initWithFrame:[self frame]];}

这是使用auto layout时的Log

initWithCoder H:0.000000,W:0.000000
initWithFrame 0.000000—0.000000
setFrame H:44.000000,W:320.000000
awakeFromNib H:44.000000,W:320.000000
setFrame H:44.000000,W:375.000000
setFrame H:44.000000,W:375.000000


0 0
原创粉丝点击