UITableViewCell 重新排序清除子视图的背景颜色

UITableViewCell reorder clears subview's background color

这个问题已经被问过几次了,但似乎没有任何解决办法。

UITableView reorder hides background

Subviews of UITableViewCell are not visible while reordering

Reordering causing subview 's backround color to clear

我有一个带有 UILabel 的自定义表格视图单元格。当 tableview 处于编辑模式并且我拖动单元格以重新排序时,UILabel 的背景变为清晰的颜色。我还发现,如果我尝试重新排序选定的单元格(我的表格视图在编辑模式下允许多项选择),子视图的背景颜色会保留。

我在我的 CustomCell 中尝试了以下方法,但其中 none 会在单元格被拖动时覆盖子视图的背景颜色。

我希望保留子视图的背景色。有没有我错过的方法?还是苹果这样设计的?

- (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];
    }
}

您可以创建自定义 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

这对你有帮助!

为 Swift 3 添加现代解决方案。

创建一个新的 .swift 文件并创建一个自定义 UIView class:

import UIKit

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

在 Interface Builder 中,转到身份检查器并将 class 设置为闪亮的新 NeverClearView class。这将阻止它在单元格重新排序期间消失。

这个解决方案也适用于其他 UIKit 组件,例如我必须在一秒钟前为 UIStepper 做同样的事情。