我正在尝试在 UITableView 单元格中添加另一个 View Controller 。这个想法是你点击单元格,它会展开以显示更多内容——一个消息传递界面。重要的是(我认为)这是由单独的 Messaging ViewController 控制的。
在 Storyboard 中扩展单元格并让单元格内的 View 以适当的约束扩展实际上非常简单,因此我尝试通过容器将我的新 VC 添加到 TableViewCell 来将所有内容保留在 Storyboards 中。这样我就可以在容器 View 上添加约束,并通过管道从我的 Messaging VC 中获取内容。
这是错误:
Illegal Configuration: Container Views cannot be placed in elements that are repeated at runtime.
有什么方法可以解决这个问题,或者有什么方法可以将 View 从我的 viewcontroller 传送到这个 tableviewcell 并将其限制为我在 Storyboards 中设置的配置?谢谢!
最佳答案
我有同样的任务并以这种方式决定:
步骤 1. 创建子类 MyCell: UITableViewCell
。
第 2 步。 如果您使用 Self-Sizing Cells
,请在 InterfaceBuilder 中将 UIView 添加到 MyCell,然后向所有边添加高度约束和约束。设置单元格高度需要此 View 。
如果不是,请跳过此步骤并使用 heightForRowAtIndexPath
。
第 3 步。在 MyCell.h 中添加 outlet from view height constraint 和 controller 属性:
@interface MyCell: UITableViewCell
@property (weak, nonatomic) MessagingVC *controller;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *viewHeight;
@end
第 4 步。在 cellForRowAtIndexPath
中添加代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell" forIndexPath:indexPath];
// adjust this for your structure
cell.controller = [[UIStoryboard storyboardWithName:@"MessagingVC" bundle:nil] instantiateInitialViewController];
[self addChildViewController:cell.controller];
[cell.contentView addSubview:cell.controller.view];
[cell.controller didMoveToParentViewController:self];
// if you use Self-Sizing Cells
cell.viewHeight.constant = 200; // set your constant or calculate it
return cell;
}
第 5 步 添加 didEndDisplayingCell
方法:
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if ([cell isKindOfClass:[MessagingVC class]])
[((MyCell*)cell).controller removeFromParentViewController];
}
关于UITableViewCell 中的 iOS 容器 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21345629/