我已经创建了一个自定义UITableViewCell。表视图很好地显示了数据。我陷入的是当用户触摸tableview的单元格时,然后我想显示单元格的背景颜色,而不是默认的[蓝色]值,以突出显示单元格的选择。 我使用这段代码,但什么都没有发生:
cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];
我已经创建了一个自定义UITableViewCell。表视图很好地显示了数据。我陷入的是当用户触摸tableview的单元格时,然后我想显示单元格的背景颜色,而不是默认的[蓝色]值,以突出显示单元格的选择。 我使用这段代码,但什么都没有发生:
cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];
我认为你在正确的轨道上,但根据selectedBackgroundView的类定义:
对于普通样式表(UITableViewStylePlain)中的单元格,默认为nil,对于section-group表(UITableViewStyleGrouped)中的单元格,默认为非nil。
因此,如果你使用的是普通样式的表,那么你需要alloc-init一个新的UIView,有你想要的背景颜色,然后分配给selectedBackgroundView。
或者,如果你想要的是灰色背景当单元格被选中时,你可以使用这个:
cell.selectionStyle = UITableViewCellSelectionStyleGray;
在自定义单元格类中为表单元格创建一个自定义单元格。M把下面的代码,它会工作的很好。你需要把想要的颜色图像放在选择背景UIImage中。
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
UIImage *selectionBackground = [UIImage imageNamed:@"yellow_bar.png"];
UIImageView *iview=[[UIImageView alloc] initWithImage:selectionBackground];
self.selectedBackgroundView=iview;
}
不需要自定义单元格。如果你只想改变单元格的选定颜色,你可以这样做:
objective - c:
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];
迅速:
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.red
cell.selectedBackgroundView = bgColorView
我想指出的是,XIB编辑器为您提供了以下标准选项:
部分:蓝色/灰色/没有
(右边有选项的列,第4个标签,第一组“表格视图单元格”,第4个子组,3个项目中的第一个读为“选择”)
也许你想做的事情可以通过选择正确的标准选项来实现。
如果你有一个分组表,每个部分只有一个单元格,只需在代码中添加额外的一行: bgColorView.layer.cornerRadius = 10;
UIView *bgColorView = [[UIView alloc] init];
[bgColorView setBackgroundColor:[UIColor redColor]];
bgColorView.layer.cornerRadius = 10;
[cell setSelectedBackgroundView:bgColorView];
[bgColorView release];
不要忘记导入QuartzCore。
再一个提示基督教的方式显示圆角背景分组表。
如果我为单元格使用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,当用户单击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];
}
当表视图样式是普通的,这很容易,但在组样式,这是一个小麻烦,我解决它:
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中组表视图单元格的宽度
根据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;
}
如果这对你也有用,请告诉我。你可以在选定单元格的角落上打乱拐角半径的数值。
I've got a slightly different approach than everyone else that reflects the selection on touch rather than after being selected. I have a subclassed UITableViewCell. All you have to do is set the background color in the touch events, which simulates selection on touch, and then set the background color in the setSelected function. Setting the background color in the selSelected function allows for deselecting the cell. Make sure to pass the touch event to the super, otherwise the cell won't actually act as if its selected.
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++) {
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];
}
}
以下是我在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;
}
如果你正在使用一个自定义的TableViewCell,你也可以覆盖awakeFromNib:
override func awakeFromNib() {
super.awakeFromNib()
// Set background color
let view = UIView()
view.backgroundColor = UIColor.redColor()
selectedBackgroundView = view
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
UIView *view = [[UIView alloc] init];
[view setBackgroundColor:[UIColor redColor]];
[cell setSelectedBackgroundView:view];
}
我们需要在这个方法中设置所选的背景视图。
覆盖UITableViewCell的setSelected也可以。
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Set background color
let view = UIView()
view.backgroundColor = UIColor.redColor()
selectedBackgroundView = view
}
对于那些只想摆脱默认选择灰色背景的人,把这行代码放在你的cellForRowAtIndexPath func中:
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
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView reloadData];
UITableViewCell *cell=(UITableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
[cell setBackgroundColor:[UIColor orangeColor]];
}
我使用的是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;
我找到了这个解。
对于Swift 3.0:
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
}
}
}
Swift 3:对我来说,当你把它放在cellForRowAtIndexPath:方法中时,它就工作了
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]];
}
}
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
在Swift 4中,你还可以全局设置你表格单元格的背景色(从这里取):
let backgroundColorView = UIView()
backgroundColorView.backgroundColor = UIColor.red
UITableViewCell.appearance().selectedBackgroundView = backgroundColorView
快4.倍
要改变选择背景颜色为任何颜色使用Swift扩展
创建UITableView Cell扩展,如下所示
extension UITableViewCell{
func removeCellSelectionColour(){
let clearView = UIView()
clearView.backgroundColor = UIColor.clear
UITableViewCell.appearance().selectedBackgroundView = clearView
}
}
然后用单元格实例调用removeCellSelectionColour()。
斯威夫特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
}
Swift 5 - Xcode版本12.1 (12A7403)
| |第一步 将以下内容添加到AppDelegate.swift文件中
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let colorView = UIView()
colorView.backgroundColor = UIColor.lightGray
UITableViewCell.appearance().selectedBackgroundView = colorView
return true
}
|第二步| 确保在属性检查器中,单元格的内容视图背景设置为“清除颜色”(而不是“默认”)。这样做是为了不与App Delegate设置冲突。