iOSのUITableViewのセルのハイライト

今週はGLシリーズから離れて、iOSの開発に関する小ネタです。

アプリのテーマカラーに合わせて各種の色設定をデフォルトから変更したい場合が良くあります。

UITableViewのセルのハイライト時の色は下記3種類から選択する事が出来ます。
・UITableViewCellSelectionStyleBlue:青
・UITableViewCellSelectionStyleGray:灰
・UITableViewCellSelectionStyleNone:なし

上記以外の色を使用したい場合は、cellのselectedBackgroundViewに好みの色を
持つUIViewを設定してあげる事で変更する事が可能です。

CustomTableViewController.m

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];            
    if (cell == nil) {                
       cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
       UIView *backgroundView = [[UIView alloc] init] ;
       backgroundView.backgroundColor = [UIColor redColor]; // ハイライト時に赤色を設定
       cell.selectedBackgroundView = backgroundView;            
    }
    return cell;
}


ただし、UITableViewのstyleがgroupedに設定されている場合うまくいきません。
上段や下段の丸みが塗りつぶされてしまいます。


各セルの形状(上部、中部、下部、一行のみセルの4種類)に合わせた画像を用意すれば対応できますが、
いちいち画像を用意したくはありません。

色々と調べた結果、以下のサイトを参考にして解決しました。
HOW TO MAKE CUSTOM DRAWN GRADIENT BACKGROUNDS IN A GROUPED UITABLEVIEW WITH CORE GRAPHICS

要するにUIViewのdrawRectで直接描画してしまう方法です。
(上記サイトでは色変化のある背景色をセルに設定する方法でしたので、コードを少し変更し単一色に書き換えました。)

CustomTableViewController.m

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];            
    if (cell == nil) {                
       cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
       // UICellBackgroundViewクラスは上記サイトで定義されているクラス(単一色になるように一部書き換えてます。)
       UICellBackgroundView * backgroundView = [[UICellBackgroundView alloc] initWithFrame:CGRectZero];
       [backgroundView setPosition:UICellBackgroundViewPositionTop];// セルの上部が対象の場合(実際には場合分けが必要)
       cell.selectedBackgroundView = backgroundView;
    }
    return cell;
}

デフォルトの色以外の設定ももっと簡単に出来ても良さそうなものですが...
同じ場面で困っている方は参考にしてみて下さい。