【问题标题】:UITableView Cell selected Color?UITableView 单元格选择颜色?
【发布时间】:2011-01-01 05:02:40
【问题描述】:

我创建了一个自定义UITableViewCell。表格视图显示数据正常。我遇到的问题是当用户触摸 tableview 的单元格时,我想显示单元格的背景颜色,而不是默认的 [蓝色] 值以突出显示单元格的选择。 我使用此代码但没有任何反应:

cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];

【问题讨论】:

    标签: ios objective-c uitableview selection-color


    【解决方案1】:

    不需要自定义单元格。如果您只想更改单元格的选定颜色,可以这样做:

    目标-C:

    UIView *bgColorView = [[UIView alloc] init];
    bgColorView.backgroundColor = [UIColor redColor];
    [cell setSelectedBackgroundView:bgColorView];
    

    斯威夫特:

    let bgColorView = UIView()
    bgColorView.backgroundColor = UIColor.red
    cell.selectedBackgroundView = bgColorView
    

    【讨论】:

    • 这可行,但在分组的 UITableView 中,圆角会丢失。
    • @DavidcornerRadius = 7 在分组表视图中的任何位置都有效吗?如果单元格在中间怎么办?没时间测试这个。
    • 对于 swift 来说是个小错误。正确的行是 cell.selectedBackgroundView = bgColorView
    • 请注意,要使其正常工作,在情节提要(或 XIB 文件)中,您必须选择“无”以外的选定背景颜色。这与一些答案相反,即您首先需要将其设置为 None 才能工作。如果没有,它将不起作用。让我发疯,直到我想通了。谢谢。
    • 当您还使用故事板时,您将如何完成这项工作?
    【解决方案2】:

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

    对于普通样式表 (UITableViewStylePlain) 中的单元格,默认值为 nil,对于部分组表 UITableViewStyleGrouped),默认值为非 nil。

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

    或者,您可以使用:

    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    

    如果您在选择单元格时想要的只是灰色背景。希望这会有所帮助。

    【讨论】:

    • 如果您希望将与视图相关的内容留给视图,也可以在情节提要中设置此属性。
    • Swift 3 版本 : cell.selectionStyle = .gray // 你也可以使用 .none、.blue 或 .default
    • 这个答案已经很老了...在较新的 iOS 版本中是否有一些变化?我有一个简单的表格,我的 selectedBackgroundView 不是零。有趣的是,更改此视图的 backgroundColor 没有任何效果,相反,我必须用我想要的 backgroundColor 将其替换为新的 UIView 才能使其工作。
    • 你刚刚让我免于完全发疯。非常感谢!
    • 您可以像这样更改 backgroundView 的 backgroundColor 属性:cell.selectedBackgroundView?.backgroundColor = <your color
    【解决方案3】:

    可以通过 Interface Builder 中的 Storyboard 设置表格视图单元格选择背景颜色:

    【讨论】:

    • 我认为我们无法从情节提要中设置自定义颜色。需要以编程方式设置。
    【解决方案4】:

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

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

    别忘了导入 QuartzCore。

    【讨论】:

      【解决方案5】:

      Swift 3:对我来说,当你把它放在 cellForRowAtIndexPath: 方法中时它就起作用了

      let view = UIView()
      view.backgroundColor = UIColor.red
      cell.selectedBackgroundView = view
      

      【讨论】:

      • 我认为更好的放置位置是awakeFromNib() 方法(如果是自定义单元格)。
      【解决方案6】:

      以下内容适用于 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;
      }
      

      【讨论】:

      • 此代码正在泄漏内存。任何“分配”或对象创建都必须在 if (cell ==nil) { } 块中。或者每次 iOS 释放单元格时都会创建视图。
      【解决方案7】:

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

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

      【讨论】:

      • 我认为这可能比在初始化单元格时通过仅在选择一个单元格时创建 bg 视图来设置 selectedBackgroundView 更节省内存。
      【解决方案8】:

      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
              }
          }
      }
      

      cell.selectionColor = UIColor.FormaCar.blue

      【讨论】:

      • 添加 IBDesignable 和 IBInspectable
      • @MichałZiobro 如果需要,只需在 var 上添加 @IBInspectable@IBDesignable 对此没有用处。
      【解决方案9】:

      在 Swift 4 中,您还可以全局设置表格单元格的背景颜色(取自 here):

      let backgroundColorView = UIView()
      backgroundColorView.backgroundColor = UIColor.red
      UITableViewCell.appearance().selectedBackgroundView = backgroundColorView
      

      【讨论】:

        【解决方案10】:
        -(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
        {
            UIView *view = [[UIView alloc] init];
            [view setBackgroundColor:[UIColor redColor]];
            [cell setSelectedBackgroundView:view];
        }
        

        我们需要在这个方法中设置选中的背景视图。

        【讨论】:

          【解决方案11】:

          如果您想为您的单元格添加自定义突出显示颜色(并且您的单元格包含按钮、标签、图像等),我按照以下步骤操作:

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

          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];
          }
          

          【讨论】:

            【解决方案12】:

            如果您使用的是自定义 TableViewCell,您还可以覆盖awakeFromNib

            override func awakeFromNib() {
                super.awakeFromNib()
            
                // Set background color
                let view = UIView()
                view.backgroundColor = UIColor.redColor()
                selectedBackgroundView = view
            }
            

            【讨论】:

            • 不错的解决方案!谢谢
            • 我有一个不超过 10 个单元格的简单表格视图,到目前为止效果很好。
            【解决方案13】:

            斯威夫特 4+:

            在您的表格单元格

            中添加以下行
            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
            
                }
            

            【讨论】:

              【解决方案14】:

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

              部分:蓝色/灰色/无

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

              选择正确的标准选项可能会实现您想要做的事情。

              【讨论】:

              • 你是对的。由于,如果您这样做,您可以通过添加简单地更改“cellForRowAtIndexPath”中的选择颜色: UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; cell.selectedBackgroundView = [[UIView alloc] initWithFrame:CGRectZero]; cell.selectedBackgroundView.backgroundColor = [UIColor colorWithRed:(255/255) green:(0/255) blue:(0/255) alpha:0.1];
              【解决方案15】:

              Christian 为分组表格显示圆角背景的另一个提示。

              如果我使用cornerRadius = 10 作为单元格,它会显示四个角的圆形选择背景。与 table view 的默认 UI 不一样。

              所以,我想用 cornerRadius 轻松解决它。 从下面的代码可以看出,检查单元格的位置(顶部、底部、中间或顶部底部)并添加一个子层以隐藏顶部角落或底部角落。这只是显示与默认表格视图的选择背景完全相同的外观。

              我用 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];
                      }
                  }
              }
              

              【讨论】:

                【解决方案16】:

                根据UITableView 中选定单元格的自定义颜色,根据 Maciej Swic 的answer 提供很好的解决方案

                补充一点,您通常在 Cell 配置中声明 Swic 的 answer

                - (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;
                
                }
                

                让我知道这是否也适合您。您可以将cornerRadius 数字弄乱,以获得对所选单元格角落的影响。

                【讨论】:

                  【解决方案17】:

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

                  for (int section = 0; section < [self.tableView numberOfSections]; section++) {
                          for (int row = 0; row < [self.tableView numberOfRowsInSection:section]; row++) {
                              NSIndexPath* cellPath = [NSIndexPath indexPathForRow:row inSection:section];
                              UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:cellPath];
                  
                              //stuff to do with each cell
                              UIView *bgColorView = [[UIView alloc] init];
                              bgColorView.backgroundColor = [UIColor redColor];
                              [cell setSelectedBackgroundView:bgColorView];
                          }
                      } 
                  

                  【讨论】:

                    【解决方案18】:

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

                    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()
                    }
                    

                    【讨论】:

                      【解决方案19】:

                      覆盖UITableViewCellsetSelected 也可以。

                      override func setSelected(selected: Bool, animated: Bool) {
                          super.setSelected(selected, animated: animated)
                      
                          // Set background color
                          let view = UIView()
                          view.backgroundColor = UIColor.redColor()
                          selectedBackgroundView = view
                      }
                      

                      【讨论】:

                        【解决方案20】:

                        对于那些只想摆脱默认选择的灰色背景的人,请将这行代码放在你的 cellForRowAtIndexPath 函数中:

                        yourCell.selectionStyle = .None
                        

                        【讨论】:

                        • 非常感谢,这对我来说是正确的答案,而不是其他人。
                        • 如何设置像“绿色”这样的颜色,而不是设置无、蓝色或灰色。
                        【解决方案21】:

                        对于 Swift 3.0:

                        override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
                            let cell = super.tableView(tableView, cellForRowAt: indexPath)
                        
                            cell.contentView.backgroundColor = UIColor.red
                        }
                        

                        【讨论】:

                        • 不错,但只有在用户选择某些内容后才会起作用(默认选择颜色将保持在开始时)
                        【解决方案22】:

                        我使用以下方法,对我来说效果很好,

                        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
                                            }
                                        }
                                    }
                        

                        【讨论】:

                          【解决方案23】:

                          这里是分组表所需代码的重要部分。 When any of the cells in a section are selected the first row changes color.如果最初没有将 cellselectionstyle 设置为 none,那么当用户单击 row0 时,单元格更改为 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];
                          }
                          

                          【讨论】:

                            【解决方案24】:
                            [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
                            

                            确保你已经使用上面的行来使用选择效果

                            【讨论】:

                              【解决方案25】:
                              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
                              }
                              

                              【讨论】:

                              • 请为您的答案添加一些解释,以便所有未来的读者都能阅读
                              【解决方案26】:

                              如果是自定义单元格类。只需覆盖:

                              - (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]];
                                  }
                              }
                              

                              【讨论】:

                                【解决方案27】:

                                table view的样式是plain的时候很容易,但是group的样式就有点麻烦了,我是这样解决的:

                                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中分组表格视图单元格宽度的宽度

                                【讨论】:

                                  【解决方案28】:

                                  我使用的是 iOS 9.3 并通过情节提要设置颜色或设置 cell.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;
                                  

                                  我找到了这个解决方案here

                                  【讨论】:

                                    【解决方案29】:

                                    试试下面的代码。

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

                                    【讨论】:

                                      【解决方案30】:

                                      Swift 4.x

                                      要将选择背景颜色更改为任何颜色,请使用 Swift Extension

                                      如下创建 UITableView 单元扩展

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

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

                                      【讨论】:

                                        猜你喜欢
                                        • 1970-01-01
                                        • 2016-11-24
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 2023-04-03
                                        相关资源
                                        最近更新 更多