Why do all backgrounds disappear on UITableViewCell select?

前端 未结 8 1880
南笙
南笙 2020-12-02 14:22

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 (vi

8条回答
  •  渐次进展
    2020-12-02 14:51

    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.

    @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.

提交回复
热议问题