tassar
tassar

Reputation: 588

Add Subview to a zero size UIView

Here is my problem, I add a subview to my container view while container view's size is (0,0), I want my subview has fixed margin length is 4(top,right,left,bottom) in my container view. Can I achieve this goal without custom my layOutSubviews method. My code is like is

- initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        mySubview = [[UIView alloc] init];
        //how to code here????
        [myContainerView addSubview:mySubview];
    }
    return self;
}

Upvotes: 1

Views: 459

Answers (3)

nielsbot
nielsbot

Reputation: 16022

What Rob Napier said... Your own -layoutSubviews will be simple:

-(void)layoutSubviews
{
    [ super layoutSubviews ] ;

    CGRect insetBounds = CGRectInset( self.bounds, 4.0f, 4.0f ) ;
    self.<<the inset subview>>.frame = insetBounds ;
}

Upvotes: 0

Rob Napier
Rob Napier

Reputation: 299355

In iOS 6, you should be able to do this with constraints, but prior to iOS 6, I do not recommend adding subviews prior to having a non-zero frame, or if you do, I recommend using layoutSubviews to fix it. It's just not possible to have a 4-point margin inside of a zero-sized box, so it's never going to autosize correctly using springs and struts.

Upvotes: 1

Shamsudheen TK
Shamsudheen TK

Reputation: 31311

- initWithFrame:(CGRect)frame {

    self = [super initWithFrame:frame];
    if (self) {
        mySubview = [[UIView alloc] init];
        mySubview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [myContainerView addSubview:mySubview];
    }
    return self;
}

Upvotes: 0

Related Questions