ios – 关于如何将UIView屏蔽为UITableViewCell selectedBackgroundView的明确答案

我已经阅读并尝试了一些我在StackOverflow上找到的答案.我也从博客中读过并试过一些东西,但似乎没有什么能达到我想要的效果.

我创建了一个UIView并将其背景颜色设置为我想要的UITableViewCell选择颜色(而不是标准的蓝色或灰色选择颜色).我将这个UIView添加到我的单元格的selectedBackgroundView中,这很好用,我的单元格在用户选择时更改为所需的颜色.

这种方法适用于Plain UITableViews;在Grouped上不太好.在分组的UITableView上,第1个和最后一个单元格不符合剪辑/蒙版界限,如下面的屏幕截图所示.

我知道没有办法只围绕左上角和右上角.

我想严格按代码执行此操作,无需图像.

有没有人知道一个很好的小工作来改变UITableViewCell的selectedBackgroundView颜色只使用UIView而不是图像AND使第一个和最后一个单元格符合圆角边界?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"Cell";
    WCSBadgedCell   * cell = [[WCSBadgedCell alloc] initWithStyle:UITableViewCellStyleSubtitle andBadgeStyle:0 reuseIdentifier:CellIdentifier]; 
    if (cell == nil) {
        cell = [[WCSBadgedCell alloc] initWithStyle:UITableViewCellStyleDefault andBadgeStyle:0 reuseIdentifier:CellIdentifier];
    }

    UIView *bgColorView = [[UIView alloc] init];
    [bgColorView setBackgroundColor:DARKBROWN];
    [bgColorView setClipsToBounds: YES];
    [cell.layer setMasksToBounds:YES];
    [cell setSelectedBackgroundView:bgColorView];

    [cell.textLabel setText: @"Testing a Cell"];

    return cell;
}

截图

我接受了CodaFis answer,因为他添加了一条评论,指出了一个相当不错(但很冗长)的解决方案.我不得不进行相当多的改造,但最后,我现在有了我需要的selectedBackgroundView,它绕过第一个和最后一个单元格的角落,再次感谢!

Here is a n example of how I achieved this.

解决方法

我假设您使用的是UITableViewCell子类,因为您的单元格很复杂.这就是我一直在做的事情:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]))
    {
        self.clipsToBounds = YES;

        UIView* bgView = [[UIView alloc] init];
        bgView.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.25f];
        self.selectedBackgroundView = bgView;
                //other code

    }
    return self;
}

这会在单元格上产生一种深灰色覆盖,而不是所需的图像!

在您的情况下,所选单元格的确切颜色(由于方便的花花公子数字色度计)将是

[UIColor colorWithRed:106.0f/255.0f green:51.0f/255.0f blue:6.0f/255.0f alpha:1.0f];

而白色文本将是

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

    if (sel)
    {
        self.textLabel.textColor = [UIColor whiteColor];

        }
    else
    {
        self.textLabel.textColor = [UIColor colorWithRed:(105.f/255.f) green:(50.f/255.f) blue:(6.f/255.f) alpha:1.f];  

    }
}

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...