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

SFF*_*SFF 5 iphone objective-c uitableview tableviewcell ios

这个问题已被问过几次,但似乎没有任何解决方案.

UITableView重新排序隐藏背景

重新排序时,UITableViewCell的子视图不可见

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

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

我在CustomCell中尝试了以下方法,但是当拖动单元格时,它们都没有覆盖子视图的背景颜色.

我希望子视图的背景颜色保持不变.有没有我错过的方法?或者Apple以这种方式设计它?

- (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];
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

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

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

import UIKit

class NeverClearView: UIView {
    override var backgroundColor: UIColor? {
        didSet {
            if backgroundColor?.cgColor.alpha == 0 {
                backgroundColor = oldValue
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在 Interface Builder 中,转到 Identity Inspector 并将类设置为闪亮的新 NeverClearView 类。这将阻止它在单元格重新排序期间消失。

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


Vla*_*kov 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
Run Code Online (Sandbox Code Playgroud)

这会对你有帮助!