我使用UITableView来布局内容“页面”。我使用表视图的标题来布局某些图像等,我更喜欢它,如果他们没有浮动,但保持静态,因为他们做的时候,风格设置为UITableViewStyleGrouped。
除了使用UITableViewStyleGrouped,有办法做到这一点吗?我想避免使用分组,因为它增加了我所有的单元格的边缘,并要求为每个单元格禁用背景视图。我想完全控制我的布局。理想情况下,它们应该是“UITableViewStyleBareBones”,但我在文档中没有看到这个选项…
非常感谢,
实现这一点的一个可能更简单的方法:
objective - c:
CGFloat dummyViewHeight = 40;
UIView *dummyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, dummyViewHeight)];
self.tableView.tableHeaderView = dummyView;
self.tableView.contentInset = UIEdgeInsetsMake(-dummyViewHeight, 0, 0, 0);
迅速:
let dummyViewHeight = CGFloat(40)
self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: dummyViewHeight))
self.tableView.contentInset = UIEdgeInsets(top: -dummyViewHeight, left: 0, bottom: 0, right: 0)
分段标题现在将像任何常规单元格一样滚动。
还有另一种棘手的方法。主要思想是将节数加倍,第一个只显示headerView,而第二个显示真正的单元格。
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return sectionCount * 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section%2 == 0) {
return 0;
}
return _rowCount;
}
接下来需要做的是实现headerInSection委托:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
if (section%2 == 0) {
//return headerview;
}
return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
if (section%2 == 0) {
//return headerheight;
}
return 0;
}
这种方法对你的数据源也没有什么影响:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
int real_section = (int)indexPath.section / 2;
//your code
}
与其他方法相比,这种方法是安全的,同时不改变tableview的框架或contentInsets。
希望这能有所帮助。
代码片段仅为第一部分显示粘头。其他的节头将与单元格一起浮动。
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if section == 1 {
tableView.contentInset = .zero
}
}
func tableView(_ tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) {
if section == 0 {
tableView.contentInset = .init(top: -tableView.sectionHeaderHeight, left: 0, bottom: 0, right: 0)
}
}
**Swift 5.3 |编程**
private func buildTableView() -> UITableView {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.rowHeight = UITableView.automaticDimension
tableView.showsVerticalScrollIndicator = false
tableView.separatorStyle = .none
let dummyViewHeight: CGFloat = 80
tableView.tableFooterView = UIView(
frame: CGRect(x: .zero,
y: .zero,
width: tableView.bounds.size.width,
height: dummyViewHeight))
tableView.contentInset = UIEdgeInsets(top: .zero, left: .zero, bottom: -dummyViewHeight, right: .zero)
return tableView
}