简体   繁体   中英

programmatically add a bunch of custom view from XIB to UIStackView

I have a TagDisplayCell.xib with the associate TagDisplayCell.m. In the .m file i load the view like so.

- (id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder: aDecoder];
    if(self){
        //load the interface file from .xib
        [[NSBundle mainBundle] loadNibNamed:@"TagDisplayCell" owner:self options:nil];

        //add as subview
        [self addSubview:self.view];

        self.view.translatesAutoresizingMaskIntoConstraints = NO;

        [self addConstraint:[self pin:self.view attribute:NSLayoutAttributeTop]];
        [self addConstraint:[self pin:self.view attribute:NSLayoutAttributeLeft]];
        [self addConstraint:[self pin:self.view attribute:NSLayoutAttributeBottom]];
        [self addConstraint:[self pin:self.view attribute:NSLayoutAttributeRight]];
    }

    return self;
}

In my view controller there is a vertical UiStackView (so that the contents are stacked in rows). I want to add several instances of the TagDisplayCell to this UiStackView. Here is what i am doing.

//create all the views 
for(int i=0; i<[commentsAndTagsArray count]; i++)
{
    NSObject *obj =commentsAndTagsArray[i];
    if ([obj isKindOfClass:[Tag class]])
    {
        Tag *tempTag = ((Tag*) obj);
        TagDisplayCell *tempTagCell = [[TagDisplayCell alloc] initWithFrame:frame];
        [uiStackView addSubview:tempTagCell];
    }
}

When i run this nothing displays on the screen. What am i missing here?

Update: Here is my TagDisplayCell.xib" 在此处输入图片说明

When you call initWithFrame: on a View subclass, it is not loaded from a XIB.

Perform loading of the view it in the same way like you did in your first code snippet:

TagDisplayCell *tempTagCell = (TagDisplayCell *)[[[NSBundle mainBundle] loadNibNamed:@"TagDisplay" owner:nil options:nil] firstObject];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM