【问题标题】:Mix of static and dynamic table view cells iOSiOS 静态和动态表格视图单元格的混合
【发布时间】:2014-10-14 08:17:33
【问题描述】:
我试图创建一个包含静态和动态原型单元格的表格视图。
所以,我想要实现的事情是这样的:
static
static
static
static
dynamic
...
Stackoverflow、UITableView Mix of Static and Dynamic Cells? 上的这篇帖子有点帮助,但无法涵盖我的全部问题。
我想要 4 个静态单元格,但我也想在这些单元格中包含控件并将它们连接为插座,然后在下面添加更多动态单元格。
那么这可能吗?
提前谢谢你。
编辑:到目前为止我采取的方法
创建一个仅包含静态单元格的表格视图,然后在原始表格视图中添加一个新表格视图。但是,这种方法看起来并不专业,而且,当我将数据源和委托添加到那个新的表格视图时,原来的表格视图会向下移动。
为静态和动态单元格创建两个表视图,然后将它们包含在一个视图中。这是我认为合理的方法,但是因为我是一个新手开发人员,无法找到如何解决“静态表视图应该嵌入到表视图控制器中”。
【问题讨论】:
标签:
ios
objective-c
uitableview
【解决方案1】:
您可以继承 UITableViewController 并重写 dataSource 和委托方法来很好地实现这一点。
关键是将调用转发到需要静态内容的super,并在需要动态内容时自行处理。
例如,使用 IB 以正常方式定义带有静态内容的 UITableViewController,然后按如下方式进行子类化以添加带有动态内容的单个额外部分:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [super numberOfSectionsInTableView:tableView] + 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(section < [super numberOfSectionsInTableView:tableView]) {
return [super tableView: tableView numberOfRowsInSection:section];
}
else {
return self.numberOfRowsInMyDynamicSection;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.section < [super numberOfSectionsInTableView:tableView]) {
return [super tableVIew: tableView cellForRowAtIndexPath: indexPath];
}
else {
// do your own dynamic cell management;
}
}
//etc. for the other dataSource and delegate methods
我使用这种技术创建了一个UITableViewController 子类,允许您在运行时显示/隐藏静态定义的单元格。
实现所有 dateSource/delegate 方法需要一些努力,但最终你会得到一个非常方便的 UITableViewController 子类。
【解决方案2】:
我会将静态单元创建为原型,但给它们每个不同的 cellReuseIdentifier。然后在您的 cellForRowAtIndexPath 中,使用该行的正确 cellReuseIdentifier 出列。对于具有动态数据的行,将索引偏移 4 以访问正确的数据。