1

Я создал контроллер табличного представления на раскадровке. Я хочу изменить цвет текста UILabel на зеленый, когда я нажал на выбранную строку.Как изменить цвет текста UILabel в пользовательской ячейке UITable?

Я что-то вроде этого пытаюсь, но это не работает:

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    menuItems = @[@"home", @"stamp", @"scanner", @"settings"]; 

} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 


    NSString *CellIdentifier = [menuItems objectAtIndex:indexPath.row]; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 

    // Remove seperator inset 
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) { 
     [cell setSeparatorInset:UIEdgeInsetsZero]; 
    } 

    // Prevent the cell from inheriting the Table View's margin settings 
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) { 
     [cell setPreservesSuperviewLayoutMargins:NO]; 
    } 

    // Explictly set your cell's layout margins 
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) { 
     [cell setLayoutMargins:UIEdgeInsetsZero]; 
    } 

NSLog(@"cell %@",[cell.contentView viewWithTag:1000]); 

    return cell; 
} 
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 

    NSString *CellIdentifier = [menuItems objectAtIndex:indexPath.row]; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if(indexPath.row == 0){ 

     UILabel *menu= (UILabel*)[cell.contentView viewWithTag:1000]; 
     menu.textColor = [UIColor greenColor]; 
     NSLog(@"cell clicked: %@",[cell.contentView viewWithTag:1000]); 

    } 
     //[cell.textLabel setTextColor:[UIColor greenColor]]; 
     // [self setCellColor:[UIColor greenColor] ForCell:cell]; 
    [self.tableView reloadData]; 


} 

Я ярлык сопротивление в ячейке таблицы и установить идентификатор дом, штамп, сканер ... и изменение тег до 1000

Может ли кто-нибудь сказать мне, почему цвет текста этикетки по-прежнему остается неизменным и обеспечивает решение для меня?

ответ

0

Если у вас есть несколько ярлыков в ячейке, то вам необходимо установить свой цвет отдельно Чтобы получить ячейку, которая загружается в памяти, используйте

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

удалить if(indexPath.row == 0) условия, чтобы применить цвет на каждую клетку.

и петля в cell.contentView для этикеток

(Если несколько этикеток, Вы можете также получить его по тэгу, но применить уникальный тег для каждой этикетки и получить каждый ярлык с тегом)

for (id thisLabel in cell.contentView.subviews) { 
    if ([thisLabel isKindOfClass:[UILabel class]]) { 
     UILabel *currentlabel = thisLabel; 
     [currentlabel setTextColor:[UIColor greenColor]]; 
    } 
} 

для одной метки выше цикла будет работать, но его легче получить с тегом

UILabel *currentLabel= (UILabel*)[cell.contentView viewWithTag:1000]; 
[currentLabel setTextColor:[UIColor greenColor]]; 
+0

ya, у меня есть несколько ячеек. –

+0

Для нескольких ячеек, если вы хотите применить цвет ко всем. Выполните следующие шаги. Или вы также можете создать пользовательскую ячейку и применить цвет к каждой метке. – Samir

+0

Это работает! Спасибо! Но что, если я хочу, чтобы выбранные изменения ячейки были зелеными, а другие все еще остались одного цвета? –

0

В didSelectRowAtIndexPath

UITableViewCell *cell=(UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath.row]; 
cell.(whatever your label property).textColor=[UIColor greenColor]; 

Это изменит цвет этикетки на выбранной ячейке.

+0

Что такое свойство этикетки? Я не могу перетащить ярлык и установить свойство. Извините, я просто новичок>< –

+0

NSString * CellIdentifier = [menuItems objectAtIndex: indexPath.row]; UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier forIndexPath: indexPath]; cell.textLabel.textColor = [UIColor greenColor]; –

+0

Если у вас несколько ярлыков на ячейке? –

0
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    NSString *CellIdentifier = [menuItems objectAtIndex:indexPath.row]; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 


    if (selectedRow == 0) { 
     UILabel *homeLabel= (UILabel*)[cell.contentView viewWithTag:1000]; 
     [homeLabel setTextColor:[UIColor colorWithRed:(163/255.f) green:(217/255.f) blue:(33/255.f) alpha:1.0f]]; 
    }else if (selectedRow == 3){ 
     UILabel *settingLabel= (UILabel*)[cell.contentView viewWithTag:1400]; 
     [settingLabel setTextColor:[UIColor colorWithRed:(163/255.f) green:(217/255.f) blue:(33/255.f) alpha:1.0f]]; 
    } 
    if(selectedRow!= indexPath.row){ 
     UILabel *homeLabel= (UILabel*)[cell.contentView viewWithTag:1000]; 
     [homeLabel setTextColor:[UIColor whiteColor]]; 
     UILabel *stampLabel= (UILabel*)[cell.contentView viewWithTag:1200]; 
     [stampLabel setTextColor:[UIColor whiteColor]]; 
     UILabel *scannerLabel= (UILabel*)[cell.contentView viewWithTag:1300]; 
     [scannerLabel setTextColor:[UIColor whiteColor]]; 
     UILabel *settingLabel= (UILabel*)[cell.contentView viewWithTag:1400]; 
     [settingLabel setTextColor:[UIColor whiteColor]]; 

    } 

    return cell; 
} 

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
    selectedRow = indexPath.row; 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
    if(indexPath.row == 0){ 
     UILabel *homeLabel= (UILabel*)[cell.contentView viewWithTag:1000]; 
     [homeLabel setTextColor:[UIColor colorWithRed:(163/255.f) green:(217/255.f) blue:(33/255.f) alpha:1.0f]]; 
     [self.tableView reloadData]; 
    } 
    if(indexPath.row == 1){ 
     UILabel *stampLabel= (UILabel*)[cell.contentView viewWithTag:1200]; 
     [stampLabel setTextColor:[UIColor colorWithRed:(163/255.f) green:(217/255.f) blue:(33/255.f) alpha:1.0f]]; 
     [self.tableView reloadData]; 

    } 
    if(indexPath.row == 2){ 
     UILabel *scannerLabel= (UILabel*)[cell.contentView viewWithTag:1300]; 
     [scannerLabel setTextColor:[UIColor colorWithRed:(163/255.f) green:(217/255.f) blue:(33/255.f) alpha:1.0f]]; 
     [self.tableView reloadData]; 
    } 
    if(indexPath.row == 3){ 
     UILabel *settingLabel = (UILabel*)[cell.contentView viewWithTag:1400]; 
     [settingLabel setTextColor:[UIColor colorWithRed:(163/255.f) green:(217/255.f) blue:(33/255.f) alpha:1.0f]]; 
     [self.tableView reloadData]; 
    } 


} 
Смежные вопросы