2009-07-26 35 views
13

我添加了一個文字陰影單元格在我的UITableView給他們的蝕刻外觀去除的UITableViewCell文字陰影:當它選擇

cell.textLabel.textColor = [UIColor colorWithWhite:0.2 alpha:1.000]; 
cell.textLabel.shadowColor = [UIColor whiteColor]; 
cell.textLabel.shadowOffset = CGSizeMake(0, 1); 

由於陰影顏色實際上是白色的,當行被選中並變成藍色,白色陰影變得真正可見,並使文本看起來很醜。

有沒有人知道如何在默認的單元格選擇樣式應用之前刪除陰影?

我曾嘗試:

  1. 使用-tableView:willSelectRowAtIndexPath:取消設置與cell.textLabel.shadowColor = nil的影子,但這不按時上班 - 陰影未設置得到應用了藍色選擇樣式之後。
  2. 在設置陰影之前檢查cell.selectedtableView:cellForRowAtIndexPath:之前,但這顯然不起作用,因爲單元格在選擇後未重繪。

我也嘗試覆蓋-tableView:willDisplayCell:forRowAtIndexPath:委託方法,正如凱文建議如下。從我輸入的日誌語句中,只在單元格被繪製之前調用此代理方法 - 在單元格被觸摸時,它已經太晚了。這是我使用的代碼

(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSLog(@"in willDisplayCell"); 
    if (cell.highlighted || cell.selected) { 
    NSLog(@"drawing highlighed or selected cell"); 
    cell.textLabel.shadowColor = nil; 
    } else { 
    cell.textLabel.shadowColor = [UIColor whiteColor]; 
    } 
} 

回答

35

應該工作的一種方式是擴展UITableViewCell並覆蓋setSelected和setHighlighted方法,相應地設置投影狀態。這將確保它在背景高光更新的同時進行着色。

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated 
{ 
    [super setHighlighted:highlighted animated:animated]; 
    [self applyLabelDropShadow:!highlighted]; 
} 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated 
{ 
    [super setSelected:selected animated:animated]; 
    [self applyLabelDropShadow:!selected]; 
} 

- (void)applyLabelDropShadow:(BOOL)applyDropShadow 
{ 
    self.textLabel.shadowColor = applyDropShadow ? [UIColor whiteColor] : nil; 
} 
3

使用-tableView:willDisplayCell:forRowAtIndexPath:。這是在單元格實際顯示之前調用的最後一件事,因此您可以查詢其selected屬性並相應地設置文本陰影。

+2

謝謝凱文。一旦你指出`-tableView:willDisplayCell:forRowAtIndexPath:`out,我就會讀到這個文檔,聽起來它應該做到這一點,但事實並非如此。我認爲`-tableView:willDisplayCell:forRowAtIndexPath:`在單元格第一次繪製時被調用,並且當單元格被觸摸時,它已經被繪製並且委託方法不被調用。我會用我試過的代碼更新我的問題。 再次感謝! – 2009-07-27 11:08:47

+1

好吧,我認爲正確的解決方案然後是創建你自己的UITableViewCell子類並重寫`-setSelected:animated:`來根據需要調整陰影。 – 2009-07-30 07:45:50

3

您應該重寫tableView:willDisplayCell:forRowAtIndexPath:,你需要設置backgroundColor[UIColor clearColor],另外,你應該只突出顯示的國家行爲,所選擇的狀態有一個稍微不同的含義

2

我覺得這是更好的:

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated 
{ 
    [super setHighlighted:highlighted animated:animated]; 
    [self applyLabelDropShadow:!self.highlighted]; 
} 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated 
{ 
    [super setSelected:selected animated:animated]; 
    [self applyLabelDropShadow:!self.selected]; 
} 

在狀態之間變化時不會有陰影。