Ячейка UITableView выбрала цвет?
Я создал пользовательский UITableViewCell
. В представлении таблицы отображаются данные в порядке. То, что я застрял, - это когда пользователь касается ячейки таблицы, тогда я хочу показать цвет фона ячейки, кроме значений по умолчанию [синего цвета], для выделения выделения ячейки.
Я использую этот код, но ничего не происходит:
cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];
Ответы
Ответ 1
Я думаю, что вы были на правильном пути, но в соответствии с определением класса для selectedBackgroundView
:
По умолчанию используется значение nil для ячеек в таблицах с обычным стилем (UITableViewStylePlain) и non-nil для таблиц групп разделов UITableViewStyleGrouped).
Поэтому, если вы используете таблицу в обычном стиле, вам нужно выделить-init новый UIView
с желаемым цветом фона, а затем назначить его selectedBackgroundView
.
В качестве альтернативы вы можете использовать:
cell.selectionStyle = UITableViewCellSelectionStyleGray;
если все, что вам нужно, было серым фоном при выборе ячейки. Надеюсь, это поможет.
Ответ 2
Нет необходимости в пользовательских ячейках. Если вы хотите изменить только выбранный цвет ячейки, вы можете сделать это:
Objective-C:
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];
Swift:
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.redColor()
cell.selectedBackgroundView = bgColorView
Свифт 3:
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.red
cell.selectedBackgroundView = bgColorView
Swift 4.x:
let bgColorView = UIView()
bgColorView.backgroundColor = .red
cell.selectedBackgroundView = bgColorView
Изменение: Обновлено для ARC
Редактировать: добавляет Swift 3
Ответ 3
Если у вас есть сгруппированная таблица с одной ячейкой для каждого раздела, просто добавьте эту дополнительную строку в код:
bgColorView.layer.cornerRadius = 10;
UIView *bgColorView = [[UIView alloc] init];
[bgColorView setBackgroundColor:[UIColor redColor]];
bgColorView.layer.cornerRadius = 10;
[cell setSelectedBackgroundView:bgColorView];
[bgColorView release];
Не забудьте импортировать QuartzCore.
Ответ 4
Табличное представление Цвет фона выбора ячейки может быть установлен через раскадровку в Интерфейсном Разработчике:
![table view cell selection color None]()
Ответ 5
Swift 3: для меня это сработало, когда вы положили его в метод cellForRowAtIndexPath:
let view = UIView()
view.backgroundColor = UIColor.red
cell.selectedBackgroundView = view
Ответ 6
В iOS 8 работает для меня.
Мне нужно установить стиль выделения UITableViewCellSelectionStyleDefault
, чтобы пользовательский цвет фона работал. Если какой-либо другой стиль, пользовательский цвет фона будет проигнорирован. Кажется, что изменения в поведении, поскольку предыдущие ответы должны установить стиль на 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;
}
Ответ 7
Создайте пользовательскую ячейку для вашей ячейки таблицы и в пользовательском классе cell.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;
}
Ответ 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
Ответ 9
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
UIView *view = [[UIView alloc] init];
[view setBackgroundColor:[UIColor redColor]];
[cell setSelectedBackgroundView:view];
}
Нам нужно установить выбранный фоновый вид в этом методе.
Ответ 10
В Swift 4 вы также можете установить цвет фона вашей ячейки таблицы глобально (взято отсюда):
let backgroundColorView = UIView()
backgroundColorView.backgroundColor = UIColor.red
UITableViewCell.appearance().selectedBackgroundView = backgroundColorView
Ответ 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
}
Ответ 13
Еще один совет о том, как по-христиански показывать фон с закругленными углами для сгруппированной таблицы.
Если я использую cornerRadius = 10
для ячейки, он показывает cornerRadius = 10
закругленными углами выделения фона. Это не то же самое с пользовательским интерфейсом по умолчанию для табличного представления.
Итак, я думаю о простом способе решить его с помощью 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];
}
}
}
Ответ 14
Хочу отметить, что редактор XIB предлагает следующие стандартные параметры:
Раздел: синий/серый/нет
(правый столбец с опциями, четвертая вкладка, первая группа "Ячейка просмотра таблицы", 4-я подгруппа, 1 из 3 элементов читает "Выбор" )
Возможно, что вы захотите сделать, выбрав правильный стандартный вариант.
Ответ 15
В соответствии с настраиваемым цветом для выбранной ячейки в UITableView
, отличное решение по Maciej Swic answer
Чтобы добавить к этому, вы объявляете 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
для эффектов на углах выбранной ячейки.
Ответ 16
У меня есть несколько иной подход, чем у всех остальных, который отражает выбор при касании, а не после его выбора. У меня есть подклассы 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()
}
Ответ 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
также работает.
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Set background color
let view = UIView()
view.backgroundColor = UIColor.redColor()
selectedBackgroundView = view
}
Ответ 19
для тех, кто просто хочет избавиться от выбранного по умолчанию серым фоном, поместите эту строку кода в функцию cellForRowAtIndexPath func:
yourCell.selectionStyle = .None
Ответ 20
для Swift 3.0:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
cell.contentView.backgroundColor = UIColor.red
}
Ответ 21
Свифт 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
}
Ответ 22
Вот важные части кода, необходимые для сгруппированной таблицы. Когда какая-либо из ячеек в секции выбрана, первая строка меняет цвет. Без первоначальной установки элемента cellselectionstyle ничто не повторяет двойную перезагрузку, когда пользователь щелкает 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];
}
Ответ 23
Я использую ниже подход и отлично работает для меня,
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
}
}
}
Ответ 24
В случае пользовательского класса ячейки. Просто переопределите:
- (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]];
}
}
Ответ 25
Swift 4.x
Для изменения цвета фона выделения на любой цвет используйте расширение Swift.
Создайте расширение ячейки UITableView, как показано ниже
extension UITableViewCell{
func removeCellSelectionColour(){
let clearView = UIView()
clearView.backgroundColor = UIColor.clear
UITableViewCell.appearance().selectedBackgroundView = clearView
}
}
Затем вызовите removeCellSelectionColour() с экземпляром ячейки.
Ответ 26
Легко, когда стиль представления таблицы прост, но в групповом стиле это немного неприятно, я решаю его:
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
Ответ 27
[cell setSelectionStyle:UITableViewCellSelectionStyleGray];
Убедитесь, что вы использовали указанную выше строку для использования эффекта выбора
Ответ 28
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
}
Ответ 29
Я использую iOS 9.3, и установка цвета через Storyboard или настройка 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;
Я нашел это решение здесь.
Ответ 30
Попробуйте следующий код.
- (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
}