LoginSignup
56
57

More than 5 years have passed since last update.

UITableViewCellの選択色を設定した場合にsubviewが消えてしまう場合の対処法

Last updated at Posted at 2013-11-26

UITableViewCellの選択色を変える場合はUITableViewCellのカスタムクラスを作成し、init内などで以下のような記述をするのが一般的だと思います。

UIView *selectedBackgroundView = [[UIView alloc] init];
selectedBackgroundView.backgroundColor = [UIColor yellowColor];
self.selectedBackgroundView = selectedBackgroundView;

しかしCellのcontentViewに空のView(例えば以下のような縦の罫線を描画するための色付きの矩形)を置いているとき、そのViewが選択時に消えてしまうことがあります。

UIView *v = [[UIView alloc] initWithFrame:CGRectMake(40, 0, 1, 40)];
v.backgroundColor = [UIColor blackColor]; // ←selectedにしたときに黒い色が消えてしまう
self.vertivalLineView = v;
[self.contentView addSubView:self.verticalLineView];

こちらに原因と対処方法がありました。
http://stackoverflow.com/questions/14468449/the-selectedbackgroundview-modifies-the-contentview-subviews

UITableViewCellは選択時にその下層Viewの色を全て透明色に変えてしまうのが原因とのこと。以下のようにsetHighlighted:animatedsetSelected:animatedメソッドをオーバーライドすれば直すことができます。

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
    [super setHighlighted:highlighted animated:animated];
    if (highlighted) {
        // subviewの背景色を復元する
        self.verticalLineView.backgroundColor = [UIColor blackColor];
    }
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    if (selected) {
        // subviewの背景色を復元する
        self.verticalLineView.backgroundColor = [UIColor blackColor];
    }
}
56
57
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
56
57