グループ化されたUITableViewのセルの背景を変更する簡単な方法

iOSアプリケーションで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

Source: https://habr.com/ru/post/J158533/


All Articles