簡體   English   中英

更改所選單元格的背景顏色?

[英]Changing background color of selected cell?

有誰知道如何使用 UITableViewCell 為每個選定的單元格更改單元格的背景顏色? 我在 TableView 的代碼中創建了這個 UITableViewCell。

更改 selectedBackgroundView 屬性是正確且最簡單的方法。 我使用以下代碼來更改選擇顏色:

// set selection color
UIView *myBackView = [[UIView alloc] initWithFrame:cell.frame];
myBackView.backgroundColor = [UIColor colorWithRed:1 green:1 blue:0.75 alpha:1];
cell.selectedBackgroundView = myBackView;
[myBackView release];

我終於設法讓它在樣式設置為分組的表格視圖中工作。

首先將所有單元格的selectionStyle屬性設置為UITableViewCellSelectionStyleNone

cell.selectionStyle = UITableViewCellSelectionStyleNone;

然后在您的表視圖委托中實現以下內容:

static NSColor *SelectedCellBGColor = ...;
static NSColor *NotSelectedCellBGColor = ...;

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSIndexPath *currentSelectedIndexPath = [tableView indexPathForSelectedRow];
    if (currentSelectedIndexPath != nil)
    {
        [[tableView cellForRowAtIndexPath:currentSelectedIndexPath] setBackgroundColor:NotSelectedCellBGColor];
    }

    return indexPath;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [[tableView cellForRowAtIndexPath:indexPath] setBackgroundColor:SelectedCellBGColor];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (cell.isSelected == YES)
    {
        [cell setBackgroundColor:SelectedCellBGColor];
    }
    else
    {
        [cell setBackgroundColor:NotSelectedCellBGColor];
    }
}

SWIFT 4、XCODE 9、IOS 11

經過一些測試后,當表視圖選擇設置為“多選”時,當取消選擇或第二次點擊單元格時,這刪除背景顏色。 當表視圖樣式設置為“分組”時也適用。

extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) {
            cell.contentView.backgroundColor = UIColor.darkGray
        }
    }
}

注意:為了使它像下面看到的那樣工作,您的單元格的 Selection 屬性可以設置為任何但無。

不同選項的外觀

風格:純色,選擇:單選

單選

風格:純色,選擇:多選

多項選擇

樣式:分組,選擇:多選

分組多項選擇

獎金 - 動畫

為了更平滑的顏色過渡,請嘗試一些動畫:

extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) {
            UIView.animate(withDuration: 0.3, animations: {
                cell.contentView.backgroundColor = UIColor.darkGray
            })
        }
    }
}

動畫色彩過渡

獎勵 - 文本和圖像更改

您可能會注意到在選擇單元格時圖標和文本顏色也會發生變化。 當您設置 UIImage 和 UILabel Highlighted 屬性時,這會自動發生

用戶界面圖像

  1. 提供兩個彩色圖像:

兩個彩色圖像

  1. 設置突出顯示的圖像屬性:

突出顯示的屬性

用戶界面標簽

只需為 Highlighted 屬性提供一種顏色:

突出顯示的顏色

// animate between regular and selected state
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];

    if (selected) {
        self.backgroundColor = [UIColor colorWithRed:234.0f/255 green:202.0f/255 blue:255.0f/255 alpha:1.0f];
    }
    else {
        self.backgroundColor = [UIColor clearColor];
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

     UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
     cell.contentView.backgroundColor = [UIColor yellowColor];

}

我創建了 UIView 並設置了單元格 selectedBackgroundView 的屬性:

UIView *v = [[UIView alloc] init];
v.backgroundColor = [UIColor redColor];
cell.selectedBackgroundView = v;

如果您在談論選定的單元格,則該屬性為-selectedBackgroundView 這將在用戶選擇您的單元格時顯示。

我有一個高度定制的 UITableViewCell。 所以我實現了我自己的單元格選擇。

cell.selectionStyle = UITableViewCellSelectionStyleNone;

我在單元格的類中創建了一個方法:

- (void)highlightCell:(BOOL)highlight
{
    if (highlight) {
        self.contentView.backgroundColor = RGB(0x355881);
        _bodyLabel.textColor = RGB(0xffffff);
        _fromLabel.textColor = RGB(0xffffff);
        _subjectLabel.textColor = RGB(0xffffff);
        _dateLabel.textColor = RGB(0xffffff);
    }
    else {
        self.contentView.backgroundColor = RGB(0xf7f7f7);;
        _bodyLabel.textColor = RGB(0xaaaaaa);
        _fromLabel.textColor = [UIColor blackColor];
        _subjectLabel.textColor = [UIColor blackColor];
        _dateLabel.textColor = RGB(0x496487);
    }
}

在 ViewWillAppear 的 UITableViewController 類中添加了這個:

NSIndexPath *tableSelection = [self.tableView indexPathForSelectedRow];
SideSwipeTableViewCell *cell = (SideSwipeTableViewCell*)[self.tableView cellForRowAtIndexPath:tableSelection];
[cell highlightCell:NO];

在 didSelectRow 中添加了這個:

SideSwipeTableViewCell *cell = (SideSwipeTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
[cell highlightCell:YES];

我在以下方面很幸運:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    bool isSelected = // enter your own code here
    if (isSelected)
    {
        [cell setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:0.75 alpha:1]];
        [cell setAccessibilityTraits:UIAccessibilityTraitSelected];
    }
    else
    {
        [cell setBackgroundColor:[UIColor clearColor]];
        [cell setAccessibilityTraits:0];
    }
}

我能夠通過創建UITableViewCell的子類並實現 setSelected:animated: 方法來解決這個問題

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
    if(selected) {
        [self setSelectionStyle:UITableViewCellSelectionStyleNone];
        [self setBackgroundColor:[UIColor greenColor]];
    } else {
        [self setBackgroundColor:[UIColor whiteColor]];
    }
}

訣竅是設置

cell.selectionStyle = UITableViewCellSelectionStyleDefault;

在實現視圖控制器中,然后在 tableViewCell 中將其設置為

[self setSelectionStyle:UITableViewCellSelectionStyleNone];

希望這可以幫助。 :)

對於 iOS7+,如果您使用的是Interface Builder,則對您的單元格進行子類化並實現:

目標-C

- (void)awakeFromNib {
    [super awakeFromNib];
    // Default Select background
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = [UIColor redColor];
    self.selectedBackgroundView = v;
}

斯威夫特 2.2

override func awakeFromNib() {
    super.awakeFromNib()
    // Default Select background
    self.selectedBackgroundView = { view in
        view.backgroundColor = .redColor()
        return view
    }(UIView())
}

這與分組調用完美配合:Implement a custom subclass of UITableViewCell

這將尊重角落等......

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    if(selected)
        [self setBackgroundColor:[UIColor colorWithRed:(245/255.0) green:(255/255.0) blue:(255/255.0) alpha:1]];
    else
        [self setBackgroundColor:[UIColor whiteColor]];

}

如果您只想刪除灰色背景色,請執行以下操作:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     [[tableView cellForRowAtIndexPath:indexPath] setSelectionStyle:UITableViewCellSelectionStyleNone];
}     

默認樣式為灰色,如果以編程方式完成,它會破壞單元格的顏色。 你可以這樣做來避免這種情況。 (在斯威夫特中)
cell.selectionStyle = .None

斯威夫特

let v = UIView()
    v.backgroundColor = self.darkerColor(color)
    cell?.selectedBackgroundView = v;

...

func darkerColor( color: UIColor) -> UIColor {
    var h = CGFloat(0)
    var s = CGFloat(0)
    var b = CGFloat(0)
    var a = CGFloat(0)
    let hueObtained = color.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
    if hueObtained {
        return UIColor(hue: h, saturation: s, brightness: b * 0.75, alpha: a)
    }
    return color
}

為我工作

UIView *customColorView = [[UIView alloc] init];
    customColorView.backgroundColor = [UIColor colorWithRed:180/255.0 
                                                      green:138/255.0 
                                                       blue:171/255.0 
                                                      alpha:0.5];
    cell.selectedBackgroundView =  customColorView;

在Swift 3中,從照亮答案轉換而來。

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    if(selected) {
        self.selectionStyle = .none
        self.backgroundColor = UIColor.green
    } else {
        self.backgroundColor = UIColor.blue
    }
}

(但是,只有通過松開手指確認選擇后,視圖才會更改)

查看Apple 示例代碼中的AdvancedTableViewCells

您將要使用復合單元格模式。

斯威夫特 5.3

在這里,我為單行做了,而沒有為單元格創建一個類。

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) {
        cell.contentView.backgroundColor = #colorLiteral(red: 0.1411764771, green: 0.3960784376, blue: 0.5647059083, alpha: 1)
    }
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) {
        cell.contentView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
    }
}

創建自定義 UITableViewCell。 在您的自定義類中覆蓋“setSelected”函數並更改contentView背景顏色。 您還可以覆蓋“setHighlighted”功能。

在斯威夫特:

class myTableViewCell: UITableViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
        // Add your color here
        self.contentView.backgroundColor = UIColor.whiteColor()
    }

    override func setHighlighted(highlighted: Bool, animated: Bool) {
        // Add your color here
        self.contentView.backgroundColor = UIColor.whiteColor()
    }
}
override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    if selected {
        self.contentView.backgroundColor = .black
    } else {
        self.contentView.backgroundColor = .white
    }
}

Swift 3, 4, 5 選擇單元格背景顏色

1)當用戶單擊單元格時僅更改突出顯示的顏色:

1.1) 內部單元類:

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code

    let backgroundView = UIView()
    backgroundView.backgroundColor = UIColor.init(white: 1.0, alpha: 0.1)
    selectedBackgroundView = backgroundView
}

1.2) 您使用自定義單元格的視圖控制器

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
}

2)如果您為選定的單元格設置顏色:

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    // Configure the view for the selected state

    if selected {
        self.backgroundColor = .darkGray
    } else {
        self.backgroundColor = .white
    }
}

這是在 Interface Builder(在 Storyboard 中)中正確執行此操作的快速方法。 將一個簡單的 UIView 拖到 UITableView 的頂部,如下所示界面視圖接下來將您單元格的selectedBackgroundView Outlet 連接到此視圖。 您甚至可以將多個單元的出口連接到這個視圖。細胞的出口

對於通過子類化UITableViewCell並使用其默認selectedBackgroundView來設置顏色的UIAppearanceiOS 7 (及更高版本?)的UIAppearance的解決方案(正確),請查看我對類似問題的回答here

- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor yellowColor];
}

- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    cell.contentView.backgroundColor = nil;
}

我已經嘗試了上述答案中的每一個,但沒有一個最適合我,

然后我研究了本機提供的方法之一,它工作正常。

首先,將 cellSelectionStyle 設置為 None 然后去尋找這個解決方案。

func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath?
{   
    let cell = tableView.cellForRow(at: indexPath);

   //cell which is getting deselected, make whatever changes that are required to make it back normal        

    cell.backgroundColor = kNormalColor;

    return indexPath;
}

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath?
{
    let cell = tableView.cellForRow(at: indexPath);

   //cell which is getting selected, make whatever changes that are required to make it selected        

    cell.backgroundColor = kSelectedColor;

    return indexPath;
}

這種方法優於其他方法的優點是:

  1. 它適用於多個單元格選擇
  2. 您可以隨心所欲地更改任何元素,不僅可以更改給定單元格被選中和取消選中時的背景顏色。
var last_selected:IndexPath!

在類中定義 last_selected:IndexPath

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! Cell
    cell.contentView.backgroundColor = UIColor.lightGray
    cell.txt.textColor = UIColor.red

    if(last_selected != nil){
        //deselect
        let deselect_cell = tableView.cellForRow(at: last_selected) as! Cell
        deselect_cell.contentView.backgroundColor = UIColor.white
        deselect_cell.txt.textColor = UIColor.black
    }

    last_selected = indexPath
}

將選擇屬性設置為無,確保 tableView 設置了“單選”並在tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell委托方法中使用此方法:

extension UITableViewCell {
    func setSelectionColor(isSelected: Bool, selectionColor: UIColor, nonSelectionColor: UIColor) {
        contentView.backgroundColor = isSelected ? selectionColor : nonSelectionColor
    }
}

斯威夫特 5.X
它也適用於單元格的附件類型更改

extension UITableViewCell{
    var selectedBackgroundColor: UIColor?{
        set{
            let customColorView = UIView()
            customColorView.backgroundColor = newValue
            selectedBackgroundView = customColorView
        }
        get{
            return selectedBackgroundView?.backgroundColor
        }
    }
}

在 UIViewController 中使用如下...

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! myCell
    cell.selectedBackgroundColor = UIColor.lightGray
    return cell
  }

我最近在更新 Swift 5 時遇到了一個問題,其中表格視圖會閃爍選擇,然后取消選擇選定的單元格。 我在這里嘗試了幾種解決方案,但都沒有奏效。 解決方案是將clearsSelectionOnViewWillAppear設置為 false。

我以前使用過 UIView 和 selectedBackgroundColor 屬性,所以我一直使用這種方法。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCell(withIdentifier: "popoverCell", for: indexPath) as! PopoverCell

  let backgroundView = UIView()
  backgroundView.backgroundColor = Color.Blue
  cell.selectedBackgroundView = backgroundView
}

下面是我需要對 Swift 5 進行的更改。屬性clearsSelectionOnViewWillAppear是我的單元格取消選擇的原因。 第一次加載時需要以下選擇。

override func viewDidLoad() {
  super.viewDidLoad()

  clearsSelectionOnViewWillAppear = false
  popoverTableView.selectRow(at: selectedIndexPath, animated: false, scrollPosition: .none)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM