UITableView
を使用する場合、多くの場合、外観を変更する必要があります。 少なくとも、セルの背景色とセパレータの色を変更します。 そして一般的に、これはリストとしての
UITableView
問題ではありませんが、グループ化された
UITableView
場合は少し重要です。
問題は、グループ化された
UITableView
セルの
backgroundColor
変更する
UITableView
結果が予想と異なることです。 解決策は
backgroundView
セルの
backgroundView
を変更することです。 多くの場合、この目的のために、事前にレンダリングされた画像と、それに応じて
UIImageView
ます。 ただし、背景色とセルの境界線を変更するだけでよい場合、この方法はかなり不便です。
そこで、セルの背景として再利用するために
UIView
サブクラスを作成しました。
UIBezierPath
の使用の
UIBezierPath
その実装は簡単です。ここにコード全体のほとんどがあります。
- (void)drawRect:(CGRect)rect { CGRect bounds = CGRectInset(self.bounds, 0.5 / [UIScreen mainScreen].scale, 0.5 / [UIScreen mainScreen].scale); UIBezierPath *path; if (position == CellPositionSingle) { path = [UIBezierPath bezierPathWithRoundedRect:bounds cornerRadius:kCornerRadius]; } else if (position == CellPositionTop) { bounds.size.height += 1; path = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(kCornerRadius, kCornerRadius)]; } else if (position == CellPositionBottom) { path = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(kCornerRadius, kCornerRadius)]; } else { bounds.size.height += 1; path = [UIBezierPath bezierPathWithRect:bounds]; } [self.fillColor setFill]; [self.borderColor setStroke]; [path fill]; [path stroke]; }
このコードの使用は簡単で、次のようなものです。
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { CellBackgroundView *backgroundView = [CellBackgroundView new]; cell.backgroundView = backgroundView; backgroundView.backgroundColor = [UIColor clearColor]; backgroundView.borderColor = self.tableView.separatorColor; backgroundView.fillColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0]; int rowsInSection = [self tableView:tableView numberOfRowsInSection:indexPath.section]; if (rowsInSection == 1) { backgroundView.position = CellPositionSingle; } else { if (indexPath.row == 0) { backgroundView.position = CellPositionTop; } else if (indexPath.row == rowsInSection - 1) { backgroundView.position = CellPositionBottom; } else { backgroundView.position = CellPositionMiddle; } } }
結果は次のようになります。

ところで、このような興味深い点-背景色を設定するときに
[UIColor colorWithPatternImage:]
を使用すると、セルの背景としてテクスチャとグラデーションを使用できます。
完全なコードはこちらから入手できますgist.github.com/4062103