UITableViewCell изменение цвета текста выбранной строки - PullRequest
60 голосов
/ 30 апреля 2011

У меня есть вид таблицы, и я хочу знать, как я могу изменить цвет текста выбранной строки, скажем, на красный?Я попробовал этот код:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell= [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];

    cell.text = [localArray objectAtIndex:indexPath.row];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    cityName = [localArray objectAtIndex:indexPath.row];

    UITableViewCell* theCell = [tableView cellForRowAtIndexPath:indexPath];
    theCell.textColor = [UIColor redColor];
    //theCell.textLabel.textColor = [UIColor redColor];

    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

(1) Когда я выбираю какую-либо строку, цвет текста меняется на красный, но когда я выбираю другую, то текст ранее выбранной строки остается красным.как я могу решить это?

(2) Когда я прокручиваю таблицу, цвет текста меняется на черный, как решить эту проблему?

Спасибо ..

Ответы [ 4 ]

201 голосов
/ 30 апреля 2011

Сделайте это за tableView:cellForRowAtIndexPath::

cell.textLabel.highlightedTextColor = [UIColor redColor];

(и больше не используйте cell.text = .... Это устарело уже почти 2 года. Вместо этого используйте cell.textLabel.text = ....)


Как Рафаэль Оливейра , упомянутый в комментариях, если selectionStyle вашей ячейки равен UITableViewCellSelectionStyleNone, это не будет работать.Проверьте раскадровку и стиль выбора.

4 голосов
/ 07 ноября 2014

Если вы хотите изменить только цвет текста, не меняя цвет фона ячейки.Вы можете использовать это. Запишите этот код в методе cellForRowAtIndexPath

UIView *selectionColor = [[UIView alloc] init];
selectionColor.backgroundColor = [UIColor clearColor];
cell.selectedBackgroundView = selectionColor;
cell.textLabel.highlightedTextColor = [UIColor redColor];
1 голос
/ 03 сентября 2015

У меня была такая же проблема, попробуйте это!

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    for (id object in cell.superview.subviews) {
        if ([object isKindOfClass:[UITableViewCell class]]) {
            UITableViewCell *cellNotSelected = (UITableViewCell*)object;
            cellNotSelected.textLabel.textColor = [UIColor blackColor];
        }
    }

    cell.textLabel.textColor = [UIColor redColor];

    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

Это может быть решением вашей (и моей) проблемы.

0 голосов
/ 08 марта 2016

Если вы уже создаете подклассы UITableViewCell, проще / чище установить цвета в методе awakeFromNib (при условии, что вы создаете экземпляр из раскадровки или xib).

@implementation MySubclassTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.selectedBackgroundView = [[UIView alloc] initWithFrame:self.frame];
    self.selectedBackgroundView.backgroundColor = [UIColor colorWithRed:0.1 green:0.308 blue:0.173 alpha:0.6];
    self.customLabel.highlightedTextColor = [UIColor whiteColor];
}

@end
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...