2011-04-30 4 views
58

나는 tableview를 가지고 있는데, 내가 선택한 행의 텍스트 색을 어떻게 변경할 수 있습니까? 그때 어떤 행을 선택하면 UITableViewCell 선택된 행의 텍스트 색 변경

- (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)이 문제를 해결하려면 검은 색으로 테이블 텍스트 색 변경을 스크롤 할 때?

감사합니다 ..

답변

193

tableView:cellForRowAtIndexPath:에서이 작업을 수행 :

cell.textLabel.highlightedTextColor = [UIColor redColor]; 

(그리고 더 이상 cell.text = ...를 사용하지 않는 그것은 지금은 거의 2 년 이상 사용되지 않고 cell.textLabel.text = ...를 사용합니다...)


의견에 언급 된대로 Raphael Oliveira은 셀의 셀렉션이 UITableViewCellSelectionStyleNone 인 경우 작동하지 않습니다. 선택 스타일에 대해서도 스토리 보드를 확인하십시오.

+0

다른 행을 선택하기 전까지는 색상이 빨간색이어야합니다! – Maulik

+0

진짜야 .... 푸른 색도 남아 있습니다 !!! – Maulik

+0

헤이 작동 괜찮아요, 고마워. –

4

셀 배경색을 변경하지 않고 텍스트 색만 변경하려는 경우. 당신은 내가 같은 문제가 있었다

UIView *selectionColor = [[UIView alloc] init]; 
selectionColor.backgroundColor = [UIColor clearColor]; 
cell.selectedBackgroundView = selectionColor; 
cell.textLabel.highlightedTextColor = [UIColor redColor]; 
+0

이 방법을 사용하고 있지만 iOS 10에서 selectedBackgroundView 색상을 설정하면 선택시 테이블 구분 기호가 사라집니다. 나는 아직도이 부작용에 대한 좋은 해결책을 찾고있다. – Shackleford

0

cellForRowAtIndexPath 방법에에서 this.Write이 코드를 사용할 수 있습니다,이 시도!

-(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

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