ios - 只有一个粘性部分的 UItableView

标签 ios swift uitableview

我有一个 UITableView,其中有很多部分。如果我将 UITableView 类型设置为普通类型,则在滚动时所有部分都会粘在顶部。

我的要求是只为第 0 部分保留标题,其他标题应该 float (就像您将样式设置为组时一样)。

另请注意,我的 TableView 具有折叠和展开功能,这是我使用这些部分所做的。

我的 UItableView 样式设置为普通

public enum UITableViewStyle : Int {
    case plain // regular table view
}

我已经使用

实现了自定义节标题
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? 

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat

非常感谢任何正确方向的提示

最佳答案

对于这种情况,有一个棘手的解决方案。我试图在 Swift 中编写解决方案,但现在我无法找到解决方案,但我已经在 Objective-C 中实现了上述解决方案。

您需要子类化 UITableView 并公开私有(private) api 并覆盖它们,这样您就可以实现您想要的。

下面是一个 TableView 的例子。

MyTableView.h

@interface MYTableView : UITableView
@property (assign,nonatomic)BOOL shouldFloatHeader;
@property (assign,nonatomic)BOOL shouldFloatFooter;
- (BOOL)allowsHeaderViewsToFloat;
- (BOOL)allowsFooterViewsToFloat;
@end

我的表格 View .m

@implementation MYTableView
- (BOOL)allowsHeaderViewsToFloat{
    return _ shouldFloatHeader;
}
- (BOOL)allowsFooterViewsToFloat{
    return shouldFloatFooter;
}
@end

现在您也可以在 swift 中使用上面的 TableView 了。我已经运行并测试了它。

现在要使第一部分具有粘性而所有其他部分不具有粘性,我们需要在这里使用一些技巧。下面是一个例子。 有 UITableViewDelegate 方法 didEndDisplayingHeader 只需实现此方法并像这样切换 shouldFloatHeader..

objective-C

-(void)tableView:(MYTableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section {
    if (section >= 1) {
        tableView.shouldFloatHeader = YES;
    }else {
        tableView.shouldFloatHeader = NO;
    }
}

swift

func tableView(_ tableView: MYTableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) {
        if section >= 1 {
            tableView.shouldFloatHeader = true
        }else {
            tableView.shouldFloatHeader = false
        }
    }

Using private API's can lead your application to reject in some cases.

关于ios - 只有一个粘性部分的 UItableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49906945/

相关文章:

Xcode 解析带有图像问题的 RSS XML

ios - 启动 UITableView 滚动到底部

ios - 创建子类并覆盖 loadView() 时 UITableViewController.tableView=nil

ios - 显示从图库中选择的视频作为预览

ios - 循环遍历一个 json 文件并填充一个数组 Swift

arrays - 按类型过滤 Swift [AnyObject] 数组

ios - 设置 WatchKit 表

android - 相关的引起错误的小部件是Scaffold

ios - 带有大标题的 UINavigationBar - 如何在 iOS 11 中找到额外的高度

ios - UITableView 由于可重用单元而混合值