我已经创建了一个自定义UITableViewCell。表视图很好地显示了数据。我陷入的是当用户触摸tableview的单元格时,然后我想显示单元格的背景颜色,而不是默认的[蓝色]值,以突出显示单元格的选择。 我使用这段代码,但什么都没有发生:
cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];
我已经创建了一个自定义UITableViewCell。表视图很好地显示了数据。我陷入的是当用户触摸tableview的单元格时,然后我想显示单元格的背景颜色,而不是默认的[蓝色]值,以突出显示单元格的选择。 我使用这段代码,但什么都没有发生:
cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];
当前回答
1-添加一个视图到单元格的内容视图。 2-右击你的单元格。 3-使添加的视图为“selectedBackgroundView”
其他回答
1-添加一个视图到单元格的内容视图。 2-右击你的单元格。 3-使添加的视图为“selectedBackgroundView”
根据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;
}
如果这对你也有用,请告诉我。你可以在选定单元格的角落上打乱拐角半径的数值。
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设置冲突。
如果您想向单元格添加自定义高亮显示的颜色(且单元格包含按钮、标签、图像等)。我按照下面的步骤:
例如,如果你想要一个选定的黄色:
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];
}
在Swift 4中,你还可以全局设置你表格单元格的背景色(从这里取):
let backgroundColorView = UIView()
backgroundColorView.backgroundColor = UIColor.red
UITableViewCell.appearance().selectedBackgroundView = backgroundColorView