2015-04-28 54 views
4

這個問題已被問幾次,但似乎沒有任何解決方案。UITableViewCell重新排序清除子視圖的背景顏色

UITableView reorder hides background

Subviews of UITableViewCell are not visible while reordering

Reordering causing subview 's backround color to clear

我有它的UILabel定製的tableview細胞。當tableview處於編輯模式,並拖動單元格重新排序時,UILabel的背景變爲清晰的顏色。我還發現,如果我嘗試對所選單元格重新排序(我的tableview允許在編輯模式下進行多選),子視圖的背景顏色將保留。

我在我的CustomCell中嘗試了下面的方法,但是當單元格被拖動時,它們都不會覆蓋子視圖的背景顏色。

我想留下子視圖的背景顏色。有沒有我錯過的方法?或者蘋果公司是這樣設計的?

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

    if (selected) { 
     if (self.isEditing) { 
      self.customLabel.backgroundColor = [UIColor blueColor]; 
     } 
     else { 
      self.customLabel.backgroundColor = [UIColor blueColor]; 
     } 
    } 
    else { 
      self.customLabel.backgroundColor = [UIColor blueColor]; 
    } 
} 

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated { 
    [super setHighlighted:highlighted animated:animated]; 

    if (highlighted) { 
     if (self.isEditing) { 
      self.customLabel.backgroundColor = [UIColor blueColor]; 
     } 
     else { 
      self.customLabel.backgroundColor = [UIColor blueColor]; 
     } 
    } 
    else { 
     self.customLabel.backgroundColor = [UIColor blueColor]; 
    } 
} 

- (void)setEditing:(BOOL)editing animated:(BOOL)animated { 
    [super setEditing:editing animated:animated]; 

    if (editing) { 
     self.customLabel.backgroundColor = [UIColor blueColor]; 
    } 
    else { 
     self.customLabel.backgroundColor = [UIColor blueColor]; 
    } 
} 

回答

1

您可以創建自定義的UILabel。並重載-drawRect。

@interface VALAbel:UILabel 
@property (nonatomic, strong) UIColor *bac_color; 
@end 


@implementation VALabel 

-(void)setBac_color:(UIColor *)bac_color 
{ 
_bac_color = bac_color; 
[self setNeedsDisplay]; 
} 

- (void)drawRect:(CGRect)rect { 
    [self.bac_color set]; 

    CGContextSetShouldAntialias(UIGraphicsGetCurrentContext(), true); 
    CGContextFillRect(UIGraphicsGetCurrentContext(), self.bounds); 

    [super drawRect:rect]; 
} 
@end 

這會幫助你!

+0

感謝您的回答!我嘗試了你的答案,現在背景保持不變,但它將背景顏色更改爲黑色。我怎樣才能改變這種顏色? – SFF

+0

您應該在單元格中創建標籤時設置顏色。 self.customLabel.bac_color = [UIColor blueColor] – VladZ

+0

謝謝!請給我一些時間。它需要一些整理,所以我會盡快回復你。看起來它會工作:) – SFF

2

增加對斯威夫特3.現代化的解決方案

創建一個新的.swift文件,並創建一個自定義UIView類:

import UIKit 

class NeverClearView: UIView { 
    override var backgroundColor: UIColor? { 
     didSet { 
      if backgroundColor?.cgColor.alpha == 0 { 
       backgroundColor = oldValue 
      } 
     } 
    } 
} 

在Interface Builder中,去身份檢查和類設置爲你閃亮的新NeverClearView類。這將會阻止它在單元重新排序期間消失。

此解決方案也適用於其他UIKit組件,例如,我必須在第二次之前爲UIStepper執行相同的操作。