Search code examples
iosobjective-cnslayoutconstraint

Increasing height constraint, stretching "Runtime added subviews"


The line mentioned with *comments is stretching the subviews that are not bound with any constraint to its parent view.

NSMutableArray* tagItemLabels=[NSMutableArray new];
    NSMutableArray* data = [NSMutableArray arrayWithObjects:@"One",@"One Hundred",@"One Hundred Eleven",@"Thousand One Hundered",@"two",@"Three", nil];

    for (NSString* title in data) {

        MSTag * tagItem=[[[NSBundle mainBundle] loadNibNamed:@"MSTag" owner:self options:kNilOptions] objectAtIndex:0];
        [tagItem.lblTitle setText:title];
        [self.tagView addSubview:tagItem];

        CGRect frame = tagItem.frame;
        //frame.size.height=30;

        CGSize expectedLabelSize = [title sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]}];

        if (tagItemLabels.count<=0) {
            frame.origin.x=8;
            frame.origin.y=8;
            frame.size.width=expectedLabelSize.width+70;
            frame.size.height=30;
        }else{
            frame=((UIView*)([tagItemLabels lastObject])).frame;
            frame.origin.x+=frame.size.width+12;
            frame.size.height=30;
            frame.size.width=expectedLabelSize.width+70;
            NSLog(@"%f==%f",frame.origin.x+tagItem.frame.size.width+12,self.tagView.frame.size.width);

            if (frame.origin.x+frame.size.width>self.tagView.frame.size.width) {
                //if (frame.origin.x+frame.size.width>self.TagView.frame.size.width) {
                frame.origin.x=8;
                frame.origin.y+=frame.size.height+8;
            }
        }

        //***If I write this line my views get streched!***//
        self.constraintTagViewHeight.constant=frame.origin.y+frame.size.height;

        [tagItem setFrame:frame];
        [tagItemLabels addObject:tagItem];
    }

enter image description here


Solution

  • It looks like XIB file has autoresizing mask set to flexible height, and thus its height changes when superview's height changes, just add

    tagItem.autoresizingMask = UIViewAutoresizingNone

    below

    MSTag * tagItem=[[[NSBundle mainBundle] loadNibNamed:@"MSTag" owner:self options:kNilOptions] objectAtIndex:0];

    this will set the correct autoresizing mask and tags will not grow in height when superview's height changes