故事板添加一个自定义视图,它有 xib 文件没有子视图
Storyboard add a custom view which has xib file has no subviews
我创建了一个带有 xib 文件的自定义 UIView
A,它可以通过以下方式正确加载:
NSArray *starsNib = [[NSBundle mainBundle] loadNibNamed:@"nibName" owner:nil options:nil];
A *starsView = starsNib[0];
[self.view addSubview:starsView];
然后在我的故事板文件中,我将此自定义视图 A 添加到 UITableViewCell
的 contentView
。当加载 tableview 时,我发现自定义视图 A 没有在 xib 文件中添加的子视图。我还发现当 A 的 initWithCoder:
returns 时,它没有子视图。
顺便说一句,在 xib 文件中,我将 parent view
和 file's owner
都设置为自定义视图 A class.
我想知道为什么会发生这种情况以及为什么在 initWithCoder:
returns?
时未加载子视图
因为视图是从故事板而不是 XIB 加载的。在情节提要中,视图是空的。
您应该从情节提要中删除视图并在代码中加载它,可能是在实例化单元格时,因为每个单元格只需要完成一次。
您可以使用 Xib 创建自定义 tableViewCell,它的文件所有者是您的自定义 UITableViewCell class,然后您可以使用 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;
}
我创建了一个带有 xib 文件的自定义 UIView
A,它可以通过以下方式正确加载:
NSArray *starsNib = [[NSBundle mainBundle] loadNibNamed:@"nibName" owner:nil options:nil];
A *starsView = starsNib[0];
[self.view addSubview:starsView];
然后在我的故事板文件中,我将此自定义视图 A 添加到 UITableViewCell
的 contentView
。当加载 tableview 时,我发现自定义视图 A 没有在 xib 文件中添加的子视图。我还发现当 A 的 initWithCoder:
returns 时,它没有子视图。
顺便说一句,在 xib 文件中,我将 parent view
和 file's owner
都设置为自定义视图 A class.
我想知道为什么会发生这种情况以及为什么在 initWithCoder:
returns?
因为视图是从故事板而不是 XIB 加载的。在情节提要中,视图是空的。
您应该从情节提要中删除视图并在代码中加载它,可能是在实例化单元格时,因为每个单元格只需要完成一次。
您可以使用 Xib 创建自定义 tableViewCell,它的文件所有者是您的自定义 UITableViewCell class,然后您可以使用 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;
}