为什么所有背景消失在UITableViewCell选择?

时间:2022-09-25 12:41:00

My current project's UITableViewCell behavior is baffling me. I have a fairly straightforward subclass of UITableViewCell. It adds a few extra elements to the base view (via [self.contentView addSubview:...] and sets background colors on the elements to have them look like black and grey rectangular boxes.

我当前项目的UITableViewCell行为令我困惑。我有一个相当简单的UITableViewCell子类。它向基本视图(通过[self])添加了一些额外的元素。contentView addSubview:…并在元素上设置背景颜色,使它们看起来像黑色和灰色的矩形框。

Because the background of the entire table has this concrete-like texture image, each cell's background needs to be transparent, even when selected, but in that case it should darken a bit. I've set a custom semi-transparent selected background to achieve this effect:

因为整个表格的背景都有这个具体的纹理图像,所以每个单元格的背景都需要是透明的,即使是被选中的,但是在这种情况下,它应该会变暗一些。为了达到这个效果,我设置了一个自定义的半透明选择背景:

UIView *background = [[[UIView alloc] initWithFrame:self.bounds] autorelease];
background.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
background.opaque = NO;

[self setSelectedBackgroundView:background];

And although that yields the right look for the background, a weird side effect happens when I select the cell; all other backgrounds are somehow turnt off. Here's a screenshot. The bottom cell looks like it should and is not selected. The top cell is selected, but it should display the black and grey rectangular areas, yet they are gone!

虽然这样就能得到正确的背景效果,但当我选择单元格时,会产生一个奇怪的副作用;所有其他的背景都是不可分割的。下面的单元格看起来应该这样,但是没有被选中。顶部单元格被选中,但是它应该显示黑色和灰色的矩形区域,但是它们已经消失了!

为什么所有背景消失在UITableViewCell选择?

Who knows what's going on here and even more important: how can I correct this?

谁知道这里发生了什么,更重要的是:我如何纠正这个?

8 个解决方案

#1


54  

What is happening is that each subview inside the TableViewCell will receive the setSelected and setHighlighted methods. The setSelected method will remove background colors but if you set it for the selected state it will be corrected.

所发生的事情是,TableViewCell中的每个子视图都将接收setSelected和se大腿点亮的方法。setSelected方法将删除背景色,但是如果你为所选的状态设置背景色,它将被改正。

For example if those are UILabels added as subviews in your customized cell, then you can add this to the setSelected method of your TableViewCell implementation code:

例如,如果这些UILabels是作为子视图添加到自定义单元中,那么您可以将其添加到TableViewCell实现代码的setSelected方法中:

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

    self.textLabel.backgroundColor = [UIColor blackColor];

}

where self.textLabel would be whatever those labels are that are shown in the picture above

自我的地方。textLabel就是上面图片中显示的标签

I'm not sure where your adding your selected view, I usually add it in the setSelected method.

我不确定您在哪里添加所选视图,我通常在setSelected方法中添加它。

Alternatively, you can subclass the UILabel and override the setHighlighted method like so:

或者,您可以对UILabel进行子类化,并覆盖se大灯方法,如下所示:

-(void)setHighlighted:(BOOL)highlighted
{
    [self setBackgroundColor:[UIColor blackColor]];
}

#2


39  

The cell highlighting process can seem complex and confusing if you don't know whats going on. I was thoroughly confused and did some extensive experimentation. Here's the notes on my findings that may help somebody (if anyone has anything to add to this or refute then please comment and I will endeavour to confirm and update)

如果你不知道发生了什么,那么高亮显示单元格的过程就会显得复杂和混乱。我彻底搞糊涂了,做了一些广泛的实验。以下是关于我的研究结果的说明,可能会帮助一些人(如果有人有什么要补充的话,请评论一下,我将尽力去证实和更新)

In the normal “not selected” state

处于正常的“未选择”状态

  • The contentView (whats in your XIB unless you coded it otherwise) is drawn normally
  • contentView(在你的XIB中,除非你对它进行编码)是正常绘制的。
  • The selectedBackgroundView is HIDDEN
  • selectedBackgroundView是隐藏的
  • The backgroundView is visible (so provided your contentView is transparent you see the backgroundView or (if you have not defined a backgroundView you'll see the background colour of the UITableView itself)
  • backgroundView是可见的(所以如果你的contentView是透明的,你会看到backgroundView或者(如果你没有定义backgroundView你会看到UITableView本身的背景颜色)

A cell is selected, the following occurs immediately with-OUT any animation:

选择一个单元格,立即发生以下情况,没有任何动画:

  • All views/subviews within the contentView have their backgroundColor cleared (or set to transparent), label etc text color's change to their selected colour
  • contentView内的所有视图/子视图都将其backgroundColor清除(或设置为透明)、标签等文本颜色更改为所选颜色。
  • The selectedBackgroundView becomes visible (this view is always the full size of the cell (a custom frame is ignored, use a subview if you need to). Also note the backgroundColor of subViews are not displayed for some reason, perhaps they're set transparent like the contentView). If you didn't define a selectedBackgroundView then Cocoa will create/insert the blue (or gray) gradient background and display this for you)
  • selectedBackgroundView变得可见(该视图始终是单元格的完整大小(一个自定义框架被忽略,如果需要,可以使用子视图)。还要注意,由于某些原因,子视图的背景颜色没有显示出来,也许它们是像contentView一样设置为透明的)。如果你没有定义selectedBackgroundView那么Cocoa会创建/插入蓝色(或灰色)渐变背景并为你显示)
  • The backgroundView is unchanged
  • backgroundView是不变

When the cell is deselected, an animation to remove the highlighting starts:

当单元格被取消选择时,一个删除高亮显示的动画开始:

  • The selectedBackgroundView alpha property is animated from 1.0 (fully opaque) to 0.0 (fully transparent).
  • selectedBackgroundView alpha属性从1.0(完全不透明)动画到0.0(完全透明)动画。
  • The backgroundView is again unchanged (so the animation looks like a crossfade between selectedBackgroundView and backgroundView)
  • 背景视图再次保持不变(因此动画看起来像selectedBackgroundView和背景视图之间的交叉渐变)
  • ONLY ONCE the animation has finished does the contentView get redrawn in the "not-selected" state and its subview backgroundColor's become visible again (this can cause your animation to look horrible so it is advisable that you don't use UIView.backgroundColor in your contentView)
  • 只有在动画完成之后,contentView才会在“未选中”状态下重新绘制,它的子视图背景颜色才会再次可见(这会导致动画看起来很糟糕,所以建议您不要使用UIView。写成backgroundColor contentView)

CONCLUSIONS:

结论:

If you need a backgroundColor to persist through out the highlight animation, don't use the backgroundColor property of UIView instead you can try (probably with-in tableview:cellForRowAtIndexPath:):

如果您需要一个背景色来持续突出显示动画,不要使用UIView的背景色属性,而是可以尝试(可能是with-in tableview:cellForRowAtIndexPath:):

A CALayer with a background color:

背景颜色:

UIColor *bgColor = [UIColor greenColor];
CALayer* layer = [CALayer layer];
layer.frame = viewThatRequiresBGColor.bounds;
layer.backgroundColor = bgColor.CGColor;
[cell.viewThatRequiresBGColor.layer addSublayer:layer];

or a CAGradientLayer:

或CAGradientLayer:

UIColor *startColor = [UIColor redColor];
UIColor *endColor = [UIColor purpleColor];
CAGradientLayer* gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = viewThatRequiresBGColor.bounds;
gradientLayer.colors = @[(id)startColor.CGColor, (id)endColor.CGColor];
gradientLayer.locations = @[[NSNumber numberWithFloat:0],[NSNumber numberWithFloat:1]];
[cell.viewThatRequiresBGColor.layer addSublayer:gradientLayer];

I've also used a CALayer.border technique to provide a custom UITableView seperator:

我也用过电压表。边界技术提供定制的uitableviewseperator:

// We have to use the borderColor/Width as opposed to just setting the 
// backgroundColor else the view becomes transparent and disappears during 
// the cell's selected/highlighted animation
UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 1024, 1)];
separatorView.layer.borderColor = [UIColor redColor].CGColor;
separatorView.layer.borderWidth = 1.0;
[cell.contentView addSubview:separatorView];

#3


16  

When you start dragging a UITableViewCell, it calls setBackgroundColor: on its subviews with a 0-alpha color. I worked around this by subclassing UIView and overriding setBackgroundColor: to ignore requests with 0-alpha colors. It feels hacky, but it's cleaner than any of the other solutions I've come across.

当您开始拖动UITableViewCell时,它会调用setBackgroundColor:在它的子视图上带有0-alpha颜色。我通过子类化UIView和重写setBackgroundColor:以0-alpha颜色忽略请求来解决这个问题。这感觉很陈腐,但它比我遇到的任何其他解决方案都干净。

@implementation NonDisappearingView

-(void)setBackgroundColor:(UIColor *)backgroundColor {
    CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
    if (alpha != 0) {
        [super setBackgroundColor:backgroundColor];
    }
}

@end

Then, I add a NonDisappearingView to my cell and add other subviews to it:

然后,我在单元格中添加了一个非消失视图,并添加了其他子视图:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"cell";    
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
        UIView *background = [cell viewWithTag:backgroundTag];
        if (background == nil) {
            background = [[NonDisappearingView alloc] initWithFrame:backgroundFrame];
            background.tag = backgroundTag;
            background.backgroundColor = backgroundColor;
            [cell addSubview:background];
        }

        // add other views as subviews of background
        ...
    }
    return cell;
}

Alternatively, you could make cell.contentView an instance of NonDisappearingView.

或者,你也可以制作cell。contentView不显示视图的实例。

#4


5  

My solution is saving the backgroundColor and restoring it after the super call.

我的解决方案是保存背景颜色并在超级调用之后恢复它。

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    UIColor *bgColor = self.textLabel.backgroundColor;
    [super setSelected:selected animated:animated];
    self.textLabel.backgroundColor = bgColor;
}

You also need to do the same thing with -setHighlighted:animated:.

你还需要用- se大灯:animated:。

#5


2  

I created a UITableViewCell category/extension that allows you to turn on and off this transparency "feature".

我创建了一个UITableViewCell类别/扩展,允许您打开和关闭这个透明的“特性”。

You can find KeepBackgroundCell on GitHub

Install it via CocoaPods by adding the following line to your Podfile:

通过可可粉进行安装,在你的播客中添加以下内容:

pod 'KeepBackgroundCell'

Usage:

Swift

斯威夫特

let cell = <Initialize Cell>
cell.keepSubviewBackground = true  // Turn  transparency "feature" off
cell.keepSubviewBackground = false // Leave transparency "feature" on

Objective-C

objective - c

UITableViewCell* cell = <Initialize Cell>
cell.keepSubviewBackground = YES;  // Turn  transparency "feature" off
cell.keepSubviewBackground = NO;   // Leave transparency "feature" on

#6


2  

Found a pretty elegant solution instead of messing with the tableView methods. You can create a subclass of UIView that ignores setting its background color to clear color. Code:

找到了一个非常优雅的解决方案,而不是打乱tableView方法。您可以创建UIView的子类,它忽略将背景颜色设置为清除颜色。代码:

class NeverClearView: UIView {
    override var backgroundColor: UIColor? {
        didSet {
            if UIColor.clearColor().isEqual(backgroundColor) {
                backgroundColor = oldValue
            }
        }
    }
}

Obj-C version would be similar, the main thing here is the idea

object - c版本是相似的,这里的主要内容是这个想法

#7


1  

Having read through all the existing answers, came up with an elegant solution using Swift by only subclassing UITableViewCell.

在通读了所有现有的答案后,仅通过子类化UITableViewCell,就提出了一个使用Swift的优雅解决方案。

extension UIView {
    func iterateSubViews(block: ((view: UIView) -> Void)) {
        for subview in self.subviews {
            block(view: subview)
            subview.iterateSubViews(block)
        }
    }
}

class CustomTableViewCell: UITableViewCell {
   var keepSubViewsBackgroundColorOnSelection = false

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    // MARK: Overrides
    override func setSelected(selected: Bool, animated: Bool) {
        if self.keepSubViewsBackgroundColorOnSelection {
            var bgColors = [UIView: UIColor]()
            self.contentView.iterateSubViews() { (view) in

                guard let bgColor = view.backgroundColor else {
                    return
                }

                bgColors[view] = bgColor
            }

            super.setSelected(selected, animated: animated)

            for (view, backgroundColor) in bgColors {
                view.backgroundColor = backgroundColor
            }
        } else {
            super.setSelected(selected, animated: animated)
        }
    }

    override func setHighlighted(highlighted: Bool, animated: Bool) {
        if self.keepSubViewsBackgroundColorOnSelection {
            var bgColors = [UIView: UIColor]()
            self.contentView.iterateSubViews() { (view) in
                guard let bgColor = view.backgroundColor else {
                    return
                }

                bgColors[view] = bgColor
            }

            super.setHighlighted(highlighted, animated: animated)

            for (view, backgroundColor) in bgColors {
                view.backgroundColor = backgroundColor
            }
        } else {
            super.setHighlighted(highlighted, animated: animated)
        }
    }
}

#8


0  

All we need is to override the setSelected method and change the selectedBackgroundView for the tableViewCell in the custom tableViewCell class.

我们只需要覆盖setSelected方法,并更改自定义tableViewCell类中的tableViewCell的selectedBackgroundView。

We need to add the backgroundview for the tableViewCell in cellForRowAtIndexPath method.

我们需要在cellForRowAtIndexPath方法中添加tableViewCell的backgroundview。

lCell.selectedBackgroundView = [[UIView alloc] init];

Next I have overridden the setSelected method as mentioned below.

接下来,我重写了下面提到的setSelected方法。

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

// Configure the view for the selected state

UIImageView *lBalloonView = [self viewWithTag:102];
[lBalloonView setBackgroundColor:[[UIColor hs_globalTint] colorWithAlphaComponent:0.2]];

UITextView *lMessageTextView = [self viewWithTag:103];
lMessageTextView.backgroundColor    = [UIColor clearColor];

UILabel *lTimeLabel = [self viewWithTag:104];
lTimeLabel.backgroundColor  = [UIColor clearColor];

}

Also one of the most important point to be noted is to change the tableViewCell selection style. It should not be UITableViewCellSelectionStyleNone.

还需要注意的最重要的一点是更改tableViewCell选择样式。它不应该是UITableViewCellSelectionStyleNone。

lTableViewCell.selectionStyle = UITableViewCellSelectionStyleGray;

为什么所有背景消失在UITableViewCell选择?

#1


54  

What is happening is that each subview inside the TableViewCell will receive the setSelected and setHighlighted methods. The setSelected method will remove background colors but if you set it for the selected state it will be corrected.

所发生的事情是,TableViewCell中的每个子视图都将接收setSelected和se大腿点亮的方法。setSelected方法将删除背景色,但是如果你为所选的状态设置背景色,它将被改正。

For example if those are UILabels added as subviews in your customized cell, then you can add this to the setSelected method of your TableViewCell implementation code:

例如,如果这些UILabels是作为子视图添加到自定义单元中,那么您可以将其添加到TableViewCell实现代码的setSelected方法中:

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

    self.textLabel.backgroundColor = [UIColor blackColor];

}

where self.textLabel would be whatever those labels are that are shown in the picture above

自我的地方。textLabel就是上面图片中显示的标签

I'm not sure where your adding your selected view, I usually add it in the setSelected method.

我不确定您在哪里添加所选视图,我通常在setSelected方法中添加它。

Alternatively, you can subclass the UILabel and override the setHighlighted method like so:

或者,您可以对UILabel进行子类化,并覆盖se大灯方法,如下所示:

-(void)setHighlighted:(BOOL)highlighted
{
    [self setBackgroundColor:[UIColor blackColor]];
}

#2


39  

The cell highlighting process can seem complex and confusing if you don't know whats going on. I was thoroughly confused and did some extensive experimentation. Here's the notes on my findings that may help somebody (if anyone has anything to add to this or refute then please comment and I will endeavour to confirm and update)

如果你不知道发生了什么,那么高亮显示单元格的过程就会显得复杂和混乱。我彻底搞糊涂了,做了一些广泛的实验。以下是关于我的研究结果的说明,可能会帮助一些人(如果有人有什么要补充的话,请评论一下,我将尽力去证实和更新)

In the normal “not selected” state

处于正常的“未选择”状态

  • The contentView (whats in your XIB unless you coded it otherwise) is drawn normally
  • contentView(在你的XIB中,除非你对它进行编码)是正常绘制的。
  • The selectedBackgroundView is HIDDEN
  • selectedBackgroundView是隐藏的
  • The backgroundView is visible (so provided your contentView is transparent you see the backgroundView or (if you have not defined a backgroundView you'll see the background colour of the UITableView itself)
  • backgroundView是可见的(所以如果你的contentView是透明的,你会看到backgroundView或者(如果你没有定义backgroundView你会看到UITableView本身的背景颜色)

A cell is selected, the following occurs immediately with-OUT any animation:

选择一个单元格,立即发生以下情况,没有任何动画:

  • All views/subviews within the contentView have their backgroundColor cleared (or set to transparent), label etc text color's change to their selected colour
  • contentView内的所有视图/子视图都将其backgroundColor清除(或设置为透明)、标签等文本颜色更改为所选颜色。
  • The selectedBackgroundView becomes visible (this view is always the full size of the cell (a custom frame is ignored, use a subview if you need to). Also note the backgroundColor of subViews are not displayed for some reason, perhaps they're set transparent like the contentView). If you didn't define a selectedBackgroundView then Cocoa will create/insert the blue (or gray) gradient background and display this for you)
  • selectedBackgroundView变得可见(该视图始终是单元格的完整大小(一个自定义框架被忽略,如果需要,可以使用子视图)。还要注意,由于某些原因,子视图的背景颜色没有显示出来,也许它们是像contentView一样设置为透明的)。如果你没有定义selectedBackgroundView那么Cocoa会创建/插入蓝色(或灰色)渐变背景并为你显示)
  • The backgroundView is unchanged
  • backgroundView是不变

When the cell is deselected, an animation to remove the highlighting starts:

当单元格被取消选择时,一个删除高亮显示的动画开始:

  • The selectedBackgroundView alpha property is animated from 1.0 (fully opaque) to 0.0 (fully transparent).
  • selectedBackgroundView alpha属性从1.0(完全不透明)动画到0.0(完全透明)动画。
  • The backgroundView is again unchanged (so the animation looks like a crossfade between selectedBackgroundView and backgroundView)
  • 背景视图再次保持不变(因此动画看起来像selectedBackgroundView和背景视图之间的交叉渐变)
  • ONLY ONCE the animation has finished does the contentView get redrawn in the "not-selected" state and its subview backgroundColor's become visible again (this can cause your animation to look horrible so it is advisable that you don't use UIView.backgroundColor in your contentView)
  • 只有在动画完成之后,contentView才会在“未选中”状态下重新绘制,它的子视图背景颜色才会再次可见(这会导致动画看起来很糟糕,所以建议您不要使用UIView。写成backgroundColor contentView)

CONCLUSIONS:

结论:

If you need a backgroundColor to persist through out the highlight animation, don't use the backgroundColor property of UIView instead you can try (probably with-in tableview:cellForRowAtIndexPath:):

如果您需要一个背景色来持续突出显示动画,不要使用UIView的背景色属性,而是可以尝试(可能是with-in tableview:cellForRowAtIndexPath:):

A CALayer with a background color:

背景颜色:

UIColor *bgColor = [UIColor greenColor];
CALayer* layer = [CALayer layer];
layer.frame = viewThatRequiresBGColor.bounds;
layer.backgroundColor = bgColor.CGColor;
[cell.viewThatRequiresBGColor.layer addSublayer:layer];

or a CAGradientLayer:

或CAGradientLayer:

UIColor *startColor = [UIColor redColor];
UIColor *endColor = [UIColor purpleColor];
CAGradientLayer* gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = viewThatRequiresBGColor.bounds;
gradientLayer.colors = @[(id)startColor.CGColor, (id)endColor.CGColor];
gradientLayer.locations = @[[NSNumber numberWithFloat:0],[NSNumber numberWithFloat:1]];
[cell.viewThatRequiresBGColor.layer addSublayer:gradientLayer];

I've also used a CALayer.border technique to provide a custom UITableView seperator:

我也用过电压表。边界技术提供定制的uitableviewseperator:

// We have to use the borderColor/Width as opposed to just setting the 
// backgroundColor else the view becomes transparent and disappears during 
// the cell's selected/highlighted animation
UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 1024, 1)];
separatorView.layer.borderColor = [UIColor redColor].CGColor;
separatorView.layer.borderWidth = 1.0;
[cell.contentView addSubview:separatorView];

#3


16  

When you start dragging a UITableViewCell, it calls setBackgroundColor: on its subviews with a 0-alpha color. I worked around this by subclassing UIView and overriding setBackgroundColor: to ignore requests with 0-alpha colors. It feels hacky, but it's cleaner than any of the other solutions I've come across.

当您开始拖动UITableViewCell时,它会调用setBackgroundColor:在它的子视图上带有0-alpha颜色。我通过子类化UIView和重写setBackgroundColor:以0-alpha颜色忽略请求来解决这个问题。这感觉很陈腐,但它比我遇到的任何其他解决方案都干净。

@implementation NonDisappearingView

-(void)setBackgroundColor:(UIColor *)backgroundColor {
    CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
    if (alpha != 0) {
        [super setBackgroundColor:backgroundColor];
    }
}

@end

Then, I add a NonDisappearingView to my cell and add other subviews to it:

然后,我在单元格中添加了一个非消失视图,并添加了其他子视图:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"cell";    
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
        UIView *background = [cell viewWithTag:backgroundTag];
        if (background == nil) {
            background = [[NonDisappearingView alloc] initWithFrame:backgroundFrame];
            background.tag = backgroundTag;
            background.backgroundColor = backgroundColor;
            [cell addSubview:background];
        }

        // add other views as subviews of background
        ...
    }
    return cell;
}

Alternatively, you could make cell.contentView an instance of NonDisappearingView.

或者,你也可以制作cell。contentView不显示视图的实例。

#4


5  

My solution is saving the backgroundColor and restoring it after the super call.

我的解决方案是保存背景颜色并在超级调用之后恢复它。

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    UIColor *bgColor = self.textLabel.backgroundColor;
    [super setSelected:selected animated:animated];
    self.textLabel.backgroundColor = bgColor;
}

You also need to do the same thing with -setHighlighted:animated:.

你还需要用- se大灯:animated:。

#5


2  

I created a UITableViewCell category/extension that allows you to turn on and off this transparency "feature".

我创建了一个UITableViewCell类别/扩展,允许您打开和关闭这个透明的“特性”。

You can find KeepBackgroundCell on GitHub

Install it via CocoaPods by adding the following line to your Podfile:

通过可可粉进行安装,在你的播客中添加以下内容:

pod 'KeepBackgroundCell'

Usage:

Swift

斯威夫特

let cell = <Initialize Cell>
cell.keepSubviewBackground = true  // Turn  transparency "feature" off
cell.keepSubviewBackground = false // Leave transparency "feature" on

Objective-C

objective - c

UITableViewCell* cell = <Initialize Cell>
cell.keepSubviewBackground = YES;  // Turn  transparency "feature" off
cell.keepSubviewBackground = NO;   // Leave transparency "feature" on

#6


2  

Found a pretty elegant solution instead of messing with the tableView methods. You can create a subclass of UIView that ignores setting its background color to clear color. Code:

找到了一个非常优雅的解决方案,而不是打乱tableView方法。您可以创建UIView的子类,它忽略将背景颜色设置为清除颜色。代码:

class NeverClearView: UIView {
    override var backgroundColor: UIColor? {
        didSet {
            if UIColor.clearColor().isEqual(backgroundColor) {
                backgroundColor = oldValue
            }
        }
    }
}

Obj-C version would be similar, the main thing here is the idea

object - c版本是相似的,这里的主要内容是这个想法

#7


1  

Having read through all the existing answers, came up with an elegant solution using Swift by only subclassing UITableViewCell.

在通读了所有现有的答案后,仅通过子类化UITableViewCell,就提出了一个使用Swift的优雅解决方案。

extension UIView {
    func iterateSubViews(block: ((view: UIView) -> Void)) {
        for subview in self.subviews {
            block(view: subview)
            subview.iterateSubViews(block)
        }
    }
}

class CustomTableViewCell: UITableViewCell {
   var keepSubViewsBackgroundColorOnSelection = false

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    // MARK: Overrides
    override func setSelected(selected: Bool, animated: Bool) {
        if self.keepSubViewsBackgroundColorOnSelection {
            var bgColors = [UIView: UIColor]()
            self.contentView.iterateSubViews() { (view) in

                guard let bgColor = view.backgroundColor else {
                    return
                }

                bgColors[view] = bgColor
            }

            super.setSelected(selected, animated: animated)

            for (view, backgroundColor) in bgColors {
                view.backgroundColor = backgroundColor
            }
        } else {
            super.setSelected(selected, animated: animated)
        }
    }

    override func setHighlighted(highlighted: Bool, animated: Bool) {
        if self.keepSubViewsBackgroundColorOnSelection {
            var bgColors = [UIView: UIColor]()
            self.contentView.iterateSubViews() { (view) in
                guard let bgColor = view.backgroundColor else {
                    return
                }

                bgColors[view] = bgColor
            }

            super.setHighlighted(highlighted, animated: animated)

            for (view, backgroundColor) in bgColors {
                view.backgroundColor = backgroundColor
            }
        } else {
            super.setHighlighted(highlighted, animated: animated)
        }
    }
}

#8


0  

All we need is to override the setSelected method and change the selectedBackgroundView for the tableViewCell in the custom tableViewCell class.

我们只需要覆盖setSelected方法,并更改自定义tableViewCell类中的tableViewCell的selectedBackgroundView。

We need to add the backgroundview for the tableViewCell in cellForRowAtIndexPath method.

我们需要在cellForRowAtIndexPath方法中添加tableViewCell的backgroundview。

lCell.selectedBackgroundView = [[UIView alloc] init];

Next I have overridden the setSelected method as mentioned below.

接下来,我重写了下面提到的setSelected方法。

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

// Configure the view for the selected state

UIImageView *lBalloonView = [self viewWithTag:102];
[lBalloonView setBackgroundColor:[[UIColor hs_globalTint] colorWithAlphaComponent:0.2]];

UITextView *lMessageTextView = [self viewWithTag:103];
lMessageTextView.backgroundColor    = [UIColor clearColor];

UILabel *lTimeLabel = [self viewWithTag:104];
lTimeLabel.backgroundColor  = [UIColor clearColor];

}

Also one of the most important point to be noted is to change the tableViewCell selection style. It should not be UITableViewCellSelectionStyleNone.

还需要注意的最重要的一点是更改tableViewCell选择样式。它不应该是UITableViewCellSelectionStyleNone。

lTableViewCell.selectionStyle = UITableViewCellSelectionStyleGray;

为什么所有背景消失在UITableViewCell选择?