是否可以在不创建虚拟行的情况下更改UITableView中占位符行的高度?

pix*_*eak 5 iphone objective-c ipad ios

TableView中最后一行之外的行高(如果项目数小于TableView可以一次显示的行数,那么只有视觉详细信息的空占位符行)始终与最后一行高度相同.

是否可以改变这一点而不需要添加虚拟的最后一行?

截图

rob*_*off 1

私有UITableView实例方法_spacingForExtraSeparators返回占位符行的高度。如果您不是为 App Store 编写应用程序,只需覆盖它即可。它返回一个 CGFloat。

这是一种符合 App Store 标准的不同方法(据我所知),并且可能比创建虚拟行更容易。

UITableViewlayoutSubviews经常向自己发送消息。每当添加、删除或重新排列单元格以及滚动时(也可能是其他时间),它都会执行此操作。因此,让我们覆盖layoutSubviews以绘制一个从表视图最后一部分的底部边缘开始的视图。该视图将填充看起来像占位符单元格的重复图案,并具有您定义的高度。

创建 的子类UITableView。给你的子类一个UIView *_bottomView实例变量。我们需要重写layoutSubviews,因此我们将_bottomView在该方法中延迟初始化。

@implementation MyTableView
{
    UIView *_bottomView;
}
Run Code Online (Sandbox Code Playgroud)

覆盖layoutSubviews。你在你的代码中做的第一件事就是layoutSubviews打电话,[super layoutSubviews]这样你就可以继续表现得像一个正常的UITableView.

- (void)layoutSubviews
{
    [super layoutSubviews];
Run Code Online (Sandbox Code Playgroud)

您要做的下一件事是延迟初始化_bottomView

    if (!_bottomView) {
Run Code Online (Sandbox Code Playgroud)

您需要一个模式来填充_bottomView,并且它需要看起来像占位符单元格。创建 1 像素宽的图像上下文,高度与占位符单元格的高度相同。用白色填充上下文,并在底部绘制一条分隔线(实际上是像素)。从上下文中获取图像。

        UIGraphicsBeginImageContextWithOptions(CGSizeMake(1, placeholderHeight), YES, 0);
        [[UIColor whiteColor] setFill];
        UIRectFill(CGRectMake(0, 0, 1, placeholderHeight));
        [self.separatorColor setFill];
        UIRectFill(CGRectMake(0, placeholderHeight - 1, 1, 1));
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)

接下来,创建_bottomView,将其背景“颜色”设置为该图像作为重复模式,并将其作为子视图添加到您自己中。

        _bottomView = [[UIView alloc] initWithFrame:CGRectZero];
        _bottomView.opaque = YES;
        _bottomView.backgroundColor = [UIColor colorWithPatternImage:image];
        [self addSubview:_bottomView];
    } // end of if-block
Run Code Online (Sandbox Code Playgroud)

最后,找到最后一部分的矩形。使用该矩形计算一个框架,_bottomView该框架从最后一部分的底部开始,足够高(您自己高度的两倍就足够了),并且与最后一部分的矩形一样宽。

    int lastSectionIndex = [self.dataSource numberOfSectionsInTableView:self] - 1;
    if (lastSectionIndex < 0)
        lastSectionIndex = 0;
    CGRect lastSectionRect = [self rectForSection:lastSectionIndex];
    CGRect bottomViewFrame = CGRectMake(lastSectionRect.origin.x, CGRectGetMaxY(lastSectionRect), lastSectionRect.size.width, self.bounds.size.height * 2);
    _bottomView.frame = bottomViewFrame;
Run Code Online (Sandbox Code Playgroud)

最后,确保_bottomView是最前面的子视图,这样它将透支 的UITableView占位符单元格。

    [self bringSubviewToFront:_bottomView];
} // end of layoutSubviews
Run Code Online (Sandbox Code Playgroud)

结束。

@end
Run Code Online (Sandbox Code Playgroud)