簡體   English   中英

如何在運行時以編程方式更改UITableViewCells文本顏色

[英]How do I programatically change UITableViewCells text color at runtime

我想為我的應用程序啟用“暗模式”功能,並在TableView單元格中像這樣更改文本顏色

    if ([FS isDarkModeEnabled]) {
        cell.CATEGORY.textColor = [UIColor whiteColor];
        cell.ORIGINUSER.textColor = [UIColor whiteColor];
        cell.NUMFILES.textColor = [UIColor whiteColor];
        cell.NUMTASKS.textColor = [UIColor whiteColor];
        cell.SHARECOUNT.textColor = [UIColor whiteColor];
    } 

我想我會用for循環替換上面的代碼,但是

for (id obj in [cell.contentView subviews]) {
    if ([obj isKindOfClass:[UILabel class]]) {
        NSLog(@"%@", ((UILabel *)obj).text);//<-- this spits out my storyboard placeholder text and not the acutal text for some reason.
        [((UILabel *)obj) setTextColor:[UIColor greenColor]];
    }
}

FSCategoriesTVCCell *cell2 = [self.tableView cellForRowAtIndexPath:indexPath];
for (UILabel *lbl in [cell2.contentView subviews]) {
    [lbl setTextColor:[UIColor greenColor]];
} 

但無法使其正常工作。

以上所有代碼均在- tableView:cellForRowAtIndexPath:

編輯添加一些說明

我知道如何手動更改文本顏色,我想做的是遍歷單元格的內容,並通過for循環更改顏色,而不是通過聲明每個標簽並單獨更改每個標簽來更改顏色。

或者換句話說,我想要一個for循環,而不要執行cell.Label1.textColor = blah

當用戶啟用了暗模式時,您必須通知表視圖它應該更新單元格。 為此,只需調用tableView的[tableView reloadData]方法。

選項1:加載視圖時

- (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];
  }
  cell.textLabel.textColor = [UIColor blueColor];
  cell.textLabel.text = @"highboi";
  return cell;
}

選項2:單擊或選擇表格視圖時

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
   [tableView cellForRowAtIndexPath:indexPath].textLabel.textColor = [UIColor redColor];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM