1. 程式人生 > >改變UITableView編輯狀態的選中背景顏色.

改變UITableView編輯狀態的選中背景顏色.

下面先來一個預設的UITableViewCell的選中樣式:
這裡寫圖片描述

在不需要有選中狀態(無tableView的Edit編輯狀態需要選中某個組的時候)*以直接設定UITableViewCell的selectionStyle為None就OK.但是在edit狀態的時候selectionStyle如果是None的話.那麼將無法選中

這裡寫圖片描述

選中的話又只有那麼幾種顏色狀態可供選擇.
那麼,如何去修改這個顏色狀態呢.

通過Xcode自帶的Reveal我們可以偷偷看看層級關係

這是我選中的一個Cell
這裡寫圖片描述

這是這個選中Cell有顏色的背景對應的View
這裡寫圖片描述

我們可以看到這個背景View是

    UITableViewCellSelectedBackground

型別的

在Cell的.m中我們也找到了如下的屬性

// Default is nil for cells in UITableViewStylePlain, and non-nil for UITableViewStyleGrouped. The 'selectedBackgroundView' will be added as a subview directly above the backgroundView if not nil, or behind all other views. It is added as a subview only when
the cell is selected. Calling -setSelected:animated: will cause the 'selectedBackgroundView' to animate in and out with an alpha fade. @property (nonatomic, strong, nullable) UIView *selectedBackgroundView;

我們直接設定這個View的backgroundColor屬性是沒有任何效果的.po出來的屬性如下所示
這裡寫圖片描述

既然這個selectedBackgroundView是一個UIView物件.那麼我們可以直接替換掉系統給出的預設的View.

大家應該都知道在- (void)layoutSubviews;中我們可以得到當前控制元件以及子控制元件的詳細屬性(主要是frame方面的).那麼我們可以在-(void)layoutSubViews中替換掉系統的selectedBackgroundView

- (void)layoutSubviews {
    [super layoutSubviews];
    UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
    selectedBackgroundView.backgroundColor = [UIColor redColor];
    self.selectedBackgroundView = selectedBackgroundView;
}

最後執行時選中的效果是這樣的
這裡寫圖片描述

這裡寫圖片描述