我已经创建了一个自定义UITableViewCell。表视图很好地显示了数据。我陷入的是当用户触摸tableview的单元格时,然后我想显示单元格的背景颜色,而不是默认的[蓝色]值,以突出显示单元格的选择。 我使用这段代码,但什么都没有发生:

cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];

当前回答

Swift 3.0扩展

extension UITableViewCell {
    var selectionColor: UIColor {
        set {
            let view = UIView()
            view.backgroundColor = newValue
            self.selectedBackgroundView = view
        }
        get {
            return self.selectedBackgroundView?.backgroundColor ?? UIColor.clear
        }
    }
}

细胞。selectionColor = uiccolor . formacar .blue

其他回答

我使用的是ios9.3,通过Storyboard或设置单元格设置颜色。selectionStyle不适合我,但下面的代码工作:

UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor colorWithRed:55 / 255.0 
                                                  green:141 / 255.0 
                                                   blue:211 / 255.0 
                                                  alpha:1.0];
cell.selectedBackgroundView = customColorView;

return cell;

我找到了这个解。

我认为你在正确的轨道上,但根据selectedBackgroundView的类定义:

对于普通样式表(UITableViewStylePlain)中的单元格,默认为nil,对于section-group表(UITableViewStyleGrouped)中的单元格,默认为非nil。

因此,如果你使用的是普通样式的表,那么你需要alloc-init一个新的UIView,有你想要的背景颜色,然后分配给selectedBackgroundView。

或者,如果你想要的是灰色背景当单元格被选中时,你可以使用这个:

cell.selectionStyle = UITableViewCellSelectionStyleGray;

根据UITableView中选定单元格的自定义颜色,根据Maciej Swic的答案,很棒的解决方案

为了补充这一点,你在Cell配置中声明Swic的答案通常如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

为了增加效果,您可以使用RGB值来实现自定义颜色外观,而不是系统颜色。在我的代码中,我是这样实现的:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

} 

 static NSString *CellIdentifier = @"YourCustomCellName";
 MakanTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

// Configure the cell...

if (cell == nil) {

cell = [[[NSBundle mainBundle]loadNibNamed:@"YourCustomCellClassName" owner:self options:nil]objectAtIndex:0];
                    } 

UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor colorWithRed:255.0/256.0 green:239.0/256.0 blue:49.0/256.0 alpha:1];
bgColorView.layer.cornerRadius = 7;
bgColorView.layer.masksToBounds = YES;
[cell setSelectedBackgroundView:bgColorView];


return cell;

}

如果这对你也有用,请告诉我。你可以在选定单元格的角落上打乱拐角半径的数值。

我想指出的是,XIB编辑器为您提供了以下标准选项:

部分:蓝色/灰色/没有

(右边有选项的列,第4个标签,第一组“表格视图单元格”,第4个子组,3个项目中的第一个读为“选择”)

也许你想做的事情可以通过选择正确的标准选项来实现。

快4.倍

要改变选择背景颜色为任何颜色使用Swift扩展

创建UITableView Cell扩展,如下所示

extension UITableViewCell{

    func removeCellSelectionColour(){
        let clearView = UIView()
        clearView.backgroundColor = UIColor.clear
        UITableViewCell.appearance().selectedBackgroundView = clearView
    } 

}

然后用单元格实例调用removeCellSelectionColour()。