简体   繁体   English

情节提要添加一个自定义视图,该视图的xib文件没有子视图

[英]Storyboard add a custom view which has xib file has no subviews

I create a custom UIView A with a xib file and it can be loaded correctly by: 我用xib文件创建了一个自定义UIView A,可以通过以下方式正确加载它:


    NSArray *starsNib = [[NSBundle mainBundle] loadNibNamed:@"nibName" owner:nil options:nil];
    A *starsView = starsNib[0];
    [self.view addSubview:starsView];

Then in my storyboard file, I add this custom view A to the UITableViewCell 's contentView . 然后在我的情节提要文件中,将此自定义视图A添加到UITableViewCellcontentView When the tableview is loading, I find the custom view A has no subviews which are added in the xib file. 加载tableview时,我发现定制视图A没有xib文件中添加的子视图。 I also find when the A's initWithCoder: returns, it has no child views. 我还发现当A的initWithCoder:返回时,它没有子视图。
BTW, in the xib file, I have set both the parent view and file's owner to the custom view A class. 顺便说一句,在xib文件中,我已将parent viewfile's owner都设置为自定义视图A类。
I'd like to know why this happens and why the subviews are not loaded when initWithCoder: returns? 我想知道为什么会这样,为什么initWithCoder:返回时未加载子视图?

Because the view is being loaded from the storyboard, not the XIB. 因为视图是从情节提要而不是XIB加载的。 And in the storyboard the view is empty. 在情节提要中,视图为空。

You should remove the view from the storyboard and load it in code, probably when the cell is instantiated as it only needs to be done once per cell. 您应该从情节提要中删除视图并将其加载到代码中,这可能是在实例化单元格时进行的,因为每个单元格只需执行一次即可。

You can create custom tableViewCell using Xib which has the file owner your custom UITableViewCell class and then you can use cellForRowAtIndexPath: method like 您可以使用Xib创建自定义tableViewCell,Xib具有您的自定义UITableViewCell类的文件所有者,然后您可以使用cellForRowAtIndexPath:方法,例如

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil) {
        // Load the top-level objects from the custom cell XIB.
        NSArray * starsNib = [[NSBundle mainBundle] loadNibNamed:@"nibName" owner:self options:nil];
        cell = starsNib[0];
    }
    return cell;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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