Ios UITableView单元格所选颜色?

Ios UITableView单元格所选颜色?,ios,objective-c,uitableview,selection-color,Ios,Objective C,Uitableview,Selection Color,我已经创建了一个自定义的UITableViewCell。表视图显示的数据很好。我陷入的困境是,当用户触摸tableview的单元格时,我想显示单元格的背景色,而不是突出显示单元格选择的默认[blue color]值。 我使用此代码,但什么也没发生: cell.selectedBackgroundView.backgroundColor=[UIColor blackColor]; 我认为你的思路是对的,但是根据selectedBackgroundView的类定义: 对于普通样式表(UITable

我已经创建了一个自定义的
UITableViewCell
。表视图显示的数据很好。我陷入的困境是,当用户触摸tableview的单元格时,我想显示单元格的背景色,而不是突出显示单元格选择的默认[blue color]值。 我使用此代码,但什么也没发生:

cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];

我认为你的思路是对的,但是根据
selectedBackgroundView
的类定义:

对于普通样式表(UITableViewStylePlain)中的单元格,默认值为零;对于节组表(UITableViewStyleGrouped),默认值为非零

因此,如果您使用的是普通样式表,则需要在初始化时分配一个具有所需背景颜色的新
UIView
,然后将其分配给
selectedBackgroundView

或者,您可以使用:

cell.selectionStyle = UITableViewCellSelectionStyleGray;

如果选定单元格时只需要灰色背景。希望这有帮助。

为表格单元格创建一个自定义单元格,并在自定义单元格类中。m将代码放在下面,它将正常工作。您需要将所需的彩色图像放置在
selectionBackground
ui图像中

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    UIImage *selectionBackground = [UIImage imageNamed:@"yellow_bar.png"];
    UIImageView *iview=[[UIImageView alloc] initWithImage:selectionBackground];
    self.selectedBackgroundView=iview;
}

不需要自定义单元格。如果只想更改单元格的选定颜色,可以执行以下操作:

目标-C:

UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.red
cell.selectedBackgroundView = bgColorView
Swift:

UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.red
cell.selectedBackgroundView = bgColorView

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

部分:蓝色/灰色/无

(带选项的右侧列,第四个选项卡,第一组“表格视图单元格”,第四个子组,三项中的第一项显示“选择”)


可能通过选择正确的标准选项可以实现您想要的操作。

如果您有一个分组表,每个部分只有一个单元格,只需在代码中添加这一行:
bgColorView.layer.cornerRadius=10

UIView *bgColorView = [[UIView alloc] init];
[bgColorView setBackgroundColor:[UIColor redColor]];
bgColorView.layer.cornerRadius = 10;
[cell setSelectedBackgroundView:bgColorView];
[bgColorView release]; 

别忘了导入QuartzCore。

关于Christian显示分组表格圆角背景的另一个技巧

如果我对单元格使用
cornerRadius=10
,它将显示四个角的圆角选择背景。这与表视图的默认UI不同

所以,我想一种简单的方法来解决它,方法是转弯半径。 从下面的代码中可以看到,检查单元的位置(顶部、底部、中部或顶部底部),然后再添加一个子层以隐藏上角或下角。这只是显示了与默认表视图的选择背景完全相同的外观

我用iPad
splitterview
测试了这段代码。您可以根据需要更改patchLayer的帧位置

请让我知道是否有更简单的方法来达到同样的结果

if (tableView.style == UITableViewStyleGrouped) 
{
    if (indexPath.row == 0) 
    {
        cellPosition = CellGroupPositionAtTop;
    }    
    else 
    {
        cellPosition = CellGroupPositionAtMiddle;
    }

    NSInteger numberOfRows = [tableView numberOfRowsInSection:indexPath.section];
    if (indexPath.row == numberOfRows - 1) 
    {
        if (cellPosition == CellGroupPositionAtTop) 
        {
            cellPosition = CellGroupPositionAtTopAndBottom;
        } 
        else 
        {
            cellPosition = CellGroupPositionAtBottom;
        }
    }

    if (cellPosition != CellGroupPositionAtMiddle) 
    {
        bgColorView.layer.cornerRadius = 10;
        CALayer *patchLayer;
        if (cellPosition == CellGroupPositionAtTop) 
        {
            patchLayer = [CALayer layer];
            patchLayer.frame = CGRectMake(0, 10, 302, 35);
            patchLayer.backgroundColor = YOUR_BACKGROUND_COLOR;
            [bgColorView.layer addSublayer:patchLayer];
        } 
        else if (cellPosition == CellGroupPositionAtBottom) 
        {
            patchLayer = [CALayer layer];
            patchLayer.frame = CGRectMake(0, 0, 302, 35);
            patchLayer.backgroundColor = YOUR_BACKGROUND_COLOR;
            [bgColorView.layer addSublayer:patchLayer];
        }
    }
}

下面是分组表所需代码的重要部分。选择某个区域中的任何单元格时,第一行的颜色将发生变化。在最初未将cellselectionstyle设置为none的情况下,当用户单击第0行时,会出现注释性的双重重新加载,此时单元格将更改为bgColorView,然后淡出并再次重新加载bgColorView。祝你好运,如果有更简单的方法,请告诉我

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    if ([indexPath row] == 0) 
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        UIView *bgColorView = [[UIView alloc] init];
        bgColorView.layer.cornerRadius = 7;
        bgColorView.layer.masksToBounds = YES;
        [bgColorView setBackgroundColor:[UIColor colorWithRed:.85 green:0 blue:0 alpha:1]];
        [cell setSelectedBackgroundView:bgColorView];

        UIColor *backColor = [UIColor colorWithRed:0 green:0 blue:1 alpha:1];
        cell.backgroundColor = backColor;
        UIColor *foreColor = [UIColor colorWithWhite:1 alpha:1];
        cell.textLabel.textColor = foreColor;

        cell.textLabel.text = @"row0";
    }
    else if ([indexPath row] == 1) 
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        UIColor *backColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
        cell.backgroundColor = backColor;
        UIColor *foreColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
        cell.textLabel.textColor = foreColor;

        cell.textLabel.text = @"row1";
    }
    else if ([indexPath row] == 2) 
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        UIColor *backColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
        cell.backgroundColor = backColor;
        UIColor *foreColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
        cell.textLabel.textColor = foreColor;

        cell.textLabel.text = @"row2";
    }
    return cell;
}

#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:[indexPath section]];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:path];
    [cell setSelectionStyle:UITableViewCellSelectionStyleBlue];

    [tableView selectRowAtIndexPath:path animated:YES scrollPosition:UITableViewScrollPositionNone];

}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tvStat cellForRowAtIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}

#pragma mark Table view Gestures

-(IBAction)singleTapFrom:(UIGestureRecognizer *)tapRecog
{

    CGPoint tapLoc = [tapRecog locationInView:tvStat];
    NSIndexPath *tapPath = [tvStat indexPathForRowAtPoint:tapLoc];

    NSIndexPath *seleRow = [tvStat indexPathForSelectedRow];
    if([seleRow section] != [tapPath section])
        [self tableView:tvStat didDeselectRowAtIndexPath:seleRow];
    else if (seleRow == nil )
        {}
    else if([seleRow section] == [tapPath section] || [seleRow length] != 0)
        return;

    if(!tapPath)
        [self.view endEditing:YES];

    [self tableView:tvStat didSelectRowAtIndexPath:tapPath];
}

当表视图样式为普通样式时,这很容易,但在组样式中,这有点麻烦,我通过以下方法解决:

CGFloat cellHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kGroupTableViewCellWidth+2, cellHeight)];
view.backgroundColor = kCommonHighlightedColor;
cell.selectedBackgroundView = view;
[view release];
UIRectCorner cornerFlag = 0;
CGSize radii = CGSizeMake(0, 0);
NSInteger theLastRow = --> (yourDataSourceArray.count - 1);
if (indexPath.row == 0) {
    cornerFlag = UIRectCornerTopLeft | UIRectCornerTopRight;
    radii = CGSizeMake(10, 10);
} else if (indexPath.row == theLastRow) {
    cornerFlag = UIRectCornerBottomLeft | UIRectCornerBottomRight;
    radii = CGSizeMake(10, 10);
}
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:cornerFlag cornerRadii:radii];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = maskPath.CGPath;
view.layer.mask = shapeLayer;
注意到kGroupTableViewCellWidth,我将其定义为300,它是iPhone中group table view单元格宽度的宽度

[cell setSelectionStyle:UITableViewCellSelectionStyleGray];

请确保您已经使用了上行来使用选择效果

,这是符合Maciej Swic标准的最佳解决方案

除此之外,您还可以在单元配置中声明Swic,通常在以下位置声明:

-(UITableView单元格*)tableView:(UITableView*)tableView单元格for行索引路径:(nsindepath*)indepath

为了增加效果,您可以使用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;

}

让我知道这是否也适用于你。您可以使用
角落半径
数字来显示选定单元格角落的效果。

我的方法与其他人略有不同,它在触摸时而不是被选中后反映选择。我有一个子类UITableViewCell。您所要做的就是在触摸事件中设置背景色,模拟触摸时的选择,然后在setSelected函数中设置背景色。在selSelected功能中设置背景色允许取消选择单元格。确保将触摸事件传递给super,否则电池将不会像其选定的那样实际工作

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    self.backgroundColor = UIColor(white: 0.0, alpha: 0.1)
    super.touchesBegan(touches, withEvent: event)
}

override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
    self.backgroundColor = UIColor.clearColor()
    super.touchesCancelled(touches, withEvent: event)
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
    self.backgroundColor = selected ? UIColor(white: 0.0, alpha: 0.1) : UIColor.clearColor()
}

如果要向单元格添加自定义高亮显示的颜色(单元格包含按钮、标签、图像等),我将执行以下步骤:

例如,如果您想要选定的黄色:

1) 创建一个不透明度为20%(黄色)的适合所有单元格的视图,称为backgroundselectedView

2) 在单元控制器中写入以下内容:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
     self.backgroundselectedView.alpha=1;
    [super touchesBegan:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.backgroundselectedView.alpha=0;
    [super touchesEnded:touches withEvent:event];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.backgroundSelectedImage.alpha=0;
    [super touchesCancelled:touches withEvent:event];
}

要添加所有单元格的背景(使用Maciej的答案):

for(int section=0;section<[self.tableView numberOfSections];section++){
对于(int row=0;row<[self.tableView numberofrowsinssection:section];row++){
nsindepath*cellPath=[nsindepath indexPathForRow:row-instation:section];
UITableViewCell*cell=[self.tableView cellForRowAtIndexPath:cellPath];
//与每个细胞有关的东西
UIView*bgColorView=[[UIView alloc]init];
bgColorView.backgroundColor=[UIColor redColor];
[单元格设置选定背景视图:bgColorView];
}
} 

以下内容在iOS 8中适用

我必须将选择样式设置为
UITableViewCellSelectionStyleDefault
,自定义背景色才能工作。如果使用任何其他样式,则将忽略自定义背景色。由于之前的答案需要将style设置为none,行为似乎发生了变化

单元格的完整代码如下所示:

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

    // This is how you change the background color
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    UIView *bgColorView = [[UIView alloc] init];
    bgColorView.backgroundColor = [UIColor redColor];
    [cell setSelectedBackgroundView:bgColorView];        
    return cell;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIView *view = [[UIView alloc] init];
    [view setBackgroundColor:[UIColor redColor]];
    [cell setSelectedBackgroundView:view];
}
override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Set background color
    let view = UIView()
    view.backgroundColor = UIColor.redColor()
    selectedBackgroundView = view
}
yourCell.selectionStyle = .None
override func setSelected(selected: Bool, animated: Bool) {
    // Configure the view for the selected state

    super.setSelected(selected, animated: animated)
    let selView = UIView()

    selView.backgroundColor = UIColor( red: 5/255, green: 159/255, blue:223/255, alpha: 1.0 )
    self.selectedBackgroundView = selView
}
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;
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = super.tableView(tableView, cellForRowAt: indexPath)

    cell.contentView.backgroundColor = UIColor.red
}
class MyTableViewCell : UITableViewCell {

                var defaultStateColor:UIColor?
                var hitStateColor:UIColor?

                 override func awakeFromNib(){
                     super.awakeFromNib()
                     self.selectionStyle = .None
                 }

// if you are overriding init you should set selectionStyle = .None

                override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
                    if let hitColor = hitStateColor {
                        self.contentView.backgroundColor = hitColor
                    }
                }

                override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
                    if let defaultColor = defaultStateColor {
                        self.contentView.backgroundColor = defaultColor
                    }
                }

                override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
                    if let defaultColor = defaultStateColor {
                        self.contentView.backgroundColor = defaultColor
                    }
                }
            }
let view = UIView()
view.backgroundColor = UIColor.red
cell.selectedBackgroundView = view
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[cellIdArray objectAtIndex:indexPath.row] forIndexPath:indexPath];

    // Configure the cell...
    cell.backgroundView =
    [[UIImageView alloc] init] ;
    cell.selectedBackgroundView =[[UIImageView alloc] init];

    UIImage *rowBackground;
    UIImage *selectionBackground;


    rowBackground = [UIImage imageNamed:@"cellBackgroundDarkGrey.png"];
    selectionBackground = [UIImage imageNamed:@"selectedMenu.png"];

    ((UIImageView *)cell.backgroundView).image = rowBackground;
    ((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;



    return cell;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell


        cell.selectedBackgroundView = UIImageView()
        cell.backgroundView=UIImageView()

        let selectedBackground : UIImageView = cell.selectedBackgroundView as! UIImageView
        selectedBackground.image = UIImage.init(named:"selected.png");

        let backGround : UIImageView = cell.backgroundView as! UIImageView
        backGround.image = UIImage.init(named:"defaultimage.png");

        return cell


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

    // Configure the view for the selected state

    if (selected) {
        [self setBackgroundColor: CELL_SELECTED_BG_COLOR];
        [self.contentView setBackgroundColor: CELL_SELECTED_BG_COLOR];
    }else{
        [self setBackgroundColor: [UIColor clearColor]];
        [self.contentView setBackgroundColor: [UIColor clearColor]];
    }
}
extension UITableViewCell {
    var selectionColor: UIColor {
        set {
            let view = UIView()
            view.backgroundColor = newValue
            self.selectedBackgroundView = view
        }
        get {
            return self.selectedBackgroundView?.backgroundColor ?? UIColor.clear
        }
    }
}
let backgroundColorView = UIView()
backgroundColorView.backgroundColor = UIColor.red
UITableViewCell.appearance().selectedBackgroundView = backgroundColorView
extension UITableViewCell{

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

}
let bgColorView = UIView()
bgColorView.backgroundColor =  .red
self.selectedBackgroundView = bgColorView
override func setSelected(_ selected: Bool, animated: Bool)
    {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
        let bgColorView = UIView()
        bgColorView.backgroundColor =  .red
        self.selectedBackgroundView = bgColorView

    }