Кто-нибудь знает, как изменить цвет фона ячейки с помощью UITableViewCell для каждой выбранной ячейки? Я создал этот UITableViewCell внутри кода TableView.
Изменение цвета фона выбранной ячейки?
Ответ 1
Изменение свойства selectedBackgroundView является правильным и самым простым способом. Я использую следующий код для изменения цвета выделения:
// set selection color
UIView *myBackView = [[UIView alloc] initWithFrame:cell.frame];
myBackView.backgroundColor = [UIColor colorWithRed:1 green:1 blue:0.75 alpha:1];
cell.selectedBackgroundView = myBackView;
[myBackView release];
Ответ 2
Наконец-то мне удалось заставить это работать в представлении таблицы со стилем, установленным в Grouped.
Сначала установите для свойства selectionStyle
свойство всех ячеек UITableViewCellSelectionStyleNone
.
cell.selectionStyle = UITableViewCellSelectionStyleNone;
Затем выполните в делегате представления таблицы следующее:
static NSColor *SelectedCellBGColor = ...;
static NSColor *NotSelectedCellBGColor = ...;
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath *currentSelectedIndexPath = [tableView indexPathForSelectedRow];
if (currentSelectedIndexPath != nil)
{
[[tableView cellForRowAtIndexPath:currentSelectedIndexPath] setBackgroundColor:NotSelectedCellBGColor];
}
return indexPath;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[[tableView cellForRowAtIndexPath:indexPath] setBackgroundColor:SelectedCellBGColor];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (cell.isSelected == YES)
{
[cell setBackgroundColor:SelectedCellBGColor];
}
else
{
[cell setBackgroundColor:NotSelectedCellBGColor];
}
}
Ответ 3
// animate between regular and selected state
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
if (selected) {
self.backgroundColor = [UIColor colorWithRed:234.0f/255 green:202.0f/255 blue:255.0f/255 alpha:1.0f];
}
else {
self.backgroundColor = [UIColor clearColor];
}
}
Ответ 4
SWIFT 4, XCODE 9, IOS 11
После некоторого тестирования это БУДЕТ удалить фоновый цвет, если отменить выделение или коснуться ячейки второй раз, когда в табличном представлении Selection установлено значение "Multiple Selection". Также работает, когда стиль представления таблицы установлен на "Сгруппированный".
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.contentView.backgroundColor = UIColor.darkGray
}
}
}
Примечание. Для того чтобы это работало, как показано ниже, для свойства "Выделение ячейки" может быть задано любое значение НО.
Как это выглядит с разными вариантами
Стиль: Обычный, Выбор: Одиночный Выбор
Стиль: Обычный, Выбор: множественный выбор
Стиль: сгруппированный, выбор: множественный выбор
Бонус - Анимация
Для более плавного перехода цветов попробуйте анимацию:
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
UIView.animate(withDuration: 0.3, animations: {
cell.contentView.backgroundColor = UIColor.darkGray
})
}
}
}
Бонус - изменение текста и изображения
Вы можете заметить, что значок и цвет текста также меняются при выборе ячейки. Это происходит автоматически, когда вы устанавливаете свойства UIImage и UILabel Highlighted
UIImage
- Поставьте два цветных изображения:
- Установите свойство "Подсвеченное изображение":
UILabel
Просто укажите цвет для выделенного объекта:
Ответ 5
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor yellowColor];
}
Ответ 6
Я создал UIView и задал свойство ячейки selectedBackgroundView:
UIView *v = [[UIView alloc] init];
v.backgroundColor = [UIColor redColor];
cell.selectedBackgroundView = v;
Ответ 7
Если вы говорите об отдельных ячейках, свойство -selectedBackgroundView
. Это будет отображаться, когда пользователь выбирает вашу ячейку.
Ответ 8
Мне повезло со следующим:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
bool isSelected = // enter your own code here
if (isSelected)
{
[cell setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:0.75 alpha:1]];
[cell setAccessibilityTraits:UIAccessibilityTraitSelected];
}
else
{
[cell setBackgroundColor:[UIColor clearColor]];
[cell setAccessibilityTraits:0];
}
}
Ответ 9
У меня очень настроенный UITableViewCell. Поэтому я внедрил собственный выбор ячеек.
cell.selectionStyle = UITableViewCellSelectionStyleNone;
Я создал метод в своем классе ячеек:
- (void)highlightCell:(BOOL)highlight
{
if (highlight) {
self.contentView.backgroundColor = RGB(0x355881);
_bodyLabel.textColor = RGB(0xffffff);
_fromLabel.textColor = RGB(0xffffff);
_subjectLabel.textColor = RGB(0xffffff);
_dateLabel.textColor = RGB(0xffffff);
}
else {
self.contentView.backgroundColor = RGB(0xf7f7f7);;
_bodyLabel.textColor = RGB(0xaaaaaa);
_fromLabel.textColor = [UIColor blackColor];
_subjectLabel.textColor = [UIColor blackColor];
_dateLabel.textColor = RGB(0x496487);
}
}
В моем классе UITableViewController в ViewWillAppear добавлено следующее:
NSIndexPath *tableSelection = [self.tableView indexPathForSelectedRow];
SideSwipeTableViewCell *cell = (SideSwipeTableViewCell*)[self.tableView cellForRowAtIndexPath:tableSelection];
[cell highlightCell:NO];
В didSelectRow добавлено:
SideSwipeTableViewCell *cell = (SideSwipeTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
[cell highlightCell:YES];
Ответ 10
Для iOS7 + и если вы используете Конструктор интерфейсов, тогда подклассируйте свою ячейку и выполните:
Objective-C
- (void)awakeFromNib {
[super awakeFromNib];
// Default Select background
UIView *v = [[UIView alloc] init];
v.backgroundColor = [UIColor redColor];
self.selectedBackgroundView = v;
}
Swift 2.2
override func awakeFromNib() {
super.awakeFromNib()
// Default Select background
self.selectedBackgroundView = { view in
view.backgroundColor = .redColor()
return view
}(UIView())
}
Ответ 11
Это отлично работало с групповыми вызовами: Внедрение пользовательского подкласса UITableViewCell
Это будет уважать углы и такие...
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
if(selected)
[self setBackgroundColor:[UIColor colorWithRed:(245/255.0) green:(255/255.0) blue:(255/255.0) alpha:1]];
else
[self setBackgroundColor:[UIColor whiteColor]];
}
Ответ 12
Если вы просто хотите удалить серый цвет фона, сделайте следующее:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[[tableView cellForRowAtIndexPath:indexPath] setSelectionStyle:UITableViewCellSelectionStyleNone];
}
Ответ 13
Мне удалось решить эту проблему, создав подкласс UITableViewCell
и реализовав метод setSelected: анимированный:
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
if(selected) {
[self setSelectionStyle:UITableViewCellSelectionStyleNone];
[self setBackgroundColor:[UIColor greenColor]];
} else {
[self setBackgroundColor:[UIColor whiteColor]];
}
}
Трюк устанавливал
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
в контроллере реализующего представления, а затем в таблицеViewCell его установить как
[self setSelectionStyle:UITableViewCellSelectionStyleNone];
Надеюсь, это поможет.:)
Ответ 14
Стиль по умолчанию серый, и он разрушает цвета ячейки, если это было сделано программно. Вы можете сделать это, чтобы этого избежать. (в Свифте) cell.selectionStyle = .None
Ответ 15
Откажитесь от AdvancedTableViewCells
в Пример кода Apple.
Вы хотите использовать шаблон составной ячейки.
Ответ 16
В Swift
let v = UIView()
v.backgroundColor = self.darkerColor(color)
cell?.selectedBackgroundView = v;
...
func darkerColor( color: UIColor) -> UIColor {
var h = CGFloat(0)
var s = CGFloat(0)
var b = CGFloat(0)
var a = CGFloat(0)
let hueObtained = color.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
if hueObtained {
return UIColor(hue: h, saturation: s, brightness: b * 0.75, alpha: a)
}
return color
}
Ответ 17
в Swift 3, преобразованный из подсветки ответа.
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if(selected) {
self.selectionStyle = .none
self.backgroundColor = UIColor.green
} else {
self.backgroundColor = UIColor.blue
}
}
(однако представление изменяется только после подтверждения выбора, отпуская палец)
Ответ 18
Создайте пользовательский UITableViewCell. Внутри пользовательского класса переопределите функцию setSelected и измените цвет фона contentView. Вы также можете переопределить функцию "setHighlighted".
В Swift:
class myTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
// Add your color here
self.contentView.backgroundColor = UIColor.whiteColor()
}
override func setHighlighted(highlighted: Bool, animated: Bool) {
// Add your color here
self.contentView.backgroundColor = UIColor.whiteColor()
}
}
Ответ 19
Работает для меня
UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor colorWithRed:180/255.0
green:138/255.0
blue:171/255.0
alpha:0.5];
cell.selectedBackgroundView = customColorView;
Ответ 20
Вот быстрый способ сделать это прямо в Interface Builder (внутри раскадровки). Перетащите простой UIView в верхнюю часть вашего UITableView, как в
Затем подключите вашу ячейку
selectedBackgroundView
Выход к этому представлению. Вы даже можете подключить выходы нескольких ячеек к этому виду.
Ответ 21
Для решения, которое работает (правильно) с UIAppearance
для iOS 7 (и выше?) путем подклассификации UITableViewCell
и используя свой по умолчанию selectedBackgroundView
для установки цвета, посмотрите на мой ответ на аналогичный вопрос здесь.
Ответ 22
- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor yellowColor];
}
- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
cell.contentView.backgroundColor = nil;
}
Ответ 23
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
self.contentView.backgroundColor = .black
} else {
self.contentView.backgroundColor = .white
}
}
Ответ 24
Я пробовал каждый из ответов выше, но никто из них не подходит для меня,
тогда я просмотрел один из встроенных методов, и он работает нормально.
сначала сделайте cellSelectionStyle равным None, а затем перейдите к этому решению.
func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath?
{
let cell = tableView.cellForRow(at: indexPath);
//cell which is getting deselected, make whatever changes that are required to make it back normal
cell.backgroundColor = kNormalColor;
return indexPath;
}
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath?
{
let cell = tableView.cellForRow(at: indexPath);
//cell which is getting selected, make whatever changes that are required to make it selected
cell.backgroundColor = kSelectedColor;
return indexPath;
}
Преимущество этих методов над другими:
- Он работает для выбора нескольких ячеек
- Вы можете изменить любой элемент, какой бы вы ни хотели, не только цвет фона данной ячейки, когда он будет выбран, а также отменен.
Ответ 25
Swift 3, 4, 5 выберите цвет фона ячейки
1) Изменить только выделенный цвет, когда пользователь нажимает на ячейку:
1.1) Внутри класса клетки:
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.init(white: 1.0, alpha: 0.1)
selectedBackgroundView = backgroundView
}
1.2) Viewcontroller, который вы используете настроенную ячейку
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
2) Если вы хотите установить цвет для выбранных ячеек:
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
if selected {
self.backgroundColor = .darkGray
} else {
self.backgroundColor = .white
}
}
Ответ 26
var last_selected:IndexPath!
определить last_selected: IndexPath внутри класса
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! Cell
cell.contentView.backgroundColor = UIColor.lightGray
cell.txt.textColor = UIColor.red
if(last_selected != nil){
//deselect
let deselect_cell = tableView.cellForRow(at: last_selected) as! Cell
deselect_cell.contentView.backgroundColor = UIColor.white
deselect_cell.txt.textColor = UIColor.black
}
last_selected = indexPath
}