增加高度限制,拉伸"Runtime added subviews"

Increasing height constraint, stretching "Runtime added subviews"

*comments 提到的行正在拉伸未绑定到其父视图的任何约束的子视图。

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];
    }

看起来 XIB 文件将 autoresizing mask 设置为灵活的高度,因此它的高度会随着 superview 的高度变化而变化,只需添加

tagItem.autoresizingMask = UIViewAutoresizingNone

低于

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

这将设置正确的自动调整大小掩码,并且当 superview 的高度发生变化时,标签的高度不会增加