我使用UITableView来布局内容“页面”。我使用表视图的标题来布局某些图像等,我更喜欢它,如果他们没有浮动,但保持静态,因为他们做的时候,风格设置为UITableViewStyleGrouped。

除了使用UITableViewStyleGrouped,有办法做到这一点吗?我想避免使用分组,因为它增加了我所有的单元格的边缘,并要求为每个单元格禁用背景视图。我想完全控制我的布局。理想情况下,它们应该是“UITableViewStyleBareBones”,但我在文档中没有看到这个选项…

非常感谢,


当前回答

另一种方法是在你想要放置标题的区域之前创建一个空区域,然后把你的标题放在这个区域上。因为部分是空的,所以标题会立即滚动。

其他回答

这可以通过在UITableViewController的viewDidLoad方法中手动分配头视图来实现,而不是使用委托的viewForHeaderInSection和hightforheaderinsection。例如,在UITableViewController的子类中,你可以这样做:

- (void)viewDidLoad {
    [super viewDidLoad];

    UILabel *headerView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
    [headerView setBackgroundColor:[UIColor magentaColor]];
    [headerView setTextAlignment:NSTextAlignmentCenter];
    [headerView setText:@"Hello World"];
    [[self tableView] setTableHeaderView:headerView];
}

当用户滚动时,头视图将消失。我不知道为什么这样工作,但它似乎达到了你想要做的。

获得你想要的最简单的方法是将你的表格样式设置为UITableViewStyleGrouped, separator样式为UITableViewCellSeparatorStyleNone:

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN; // return 0.01f; would work same 
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

不要尝试返回页脚视图为nil,不要忘记设置页眉高度和页眉视图,之后你必须得到你想要的。

忽略XAK。如果你想让你的应用有机会被苹果接受,就不要探索任何私有方法。

如果您正在使用Interface Builder,这是最简单的。你可以在视图的顶部(图像所在的位置)添加一个UIView,然后在下面添加你的tableview。IB应相应地调整其大小;也就是说,tableview的顶部接触到你刚刚添加的UIView的底部,它的高度覆盖了屏幕的其余部分。

这里的想法是,如果UIView不是表格视图的一部分,它不会随着tableview滚动。即忽略tableview头。

如果你不使用界面构建器,它会更复杂一些因为你必须为tableview获得正确的定位和高度。

如果你不介意使用UICollectionView,这也可以在iOS 13.0+中使用UICollectionView列表配置并使用headerMode设置为. firstiteminsection来实现。

override func viewDidLoad() {
    super.viewDidLoad()
    var config = UICollectionLayoutListConfiguration.init(appearance: .plain)
    config.headerMode = .firstItemInSection
    let listLayout = UICollectionViewCompositionalLayout.list(using: config)
    self.collectionView.collectionViewLayout = listLayout
}

@samvermette的解决方案的变体:

/// Allows for disabling scrolling headers in plain-styled tableviews
extension UITableView {

    static let shouldScrollSectionHeadersDummyViewHeight = CGFloat(40)

    var shouldScrollSectionHeaders: Bool {
        set {
            if newValue {
                tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: bounds.size.width, height: UITableView.shouldScrollSectionHeadersDummyViewHeight))
                contentInset = UIEdgeInsets(top: -UITableView.shouldScrollSectionHeadersDummyViewHeight, left: 0, bottom: 0, right: 0)
            } else {
                tableHeaderView = nil
                contentInset = .zero
            }
        }

        get {
            return tableHeaderView != nil && contentInset.top == UITableView.shouldScrollSectionHeadersDummyViewHeight
        }
    }

}