[UITableView] 테이블 셀(UITableViewCell) 선택시 배경색 변경하기
iPhone Development 2011/03/19 22:35테이블뷰에서 특정 셀을 선택하고 있을 때에(Highlighted) 배경색을 바꿔 보겠습니다.
기본적으로 테이블에서 셀을 선택하면 아래와 같이 파란색배경으로 변경이 된다.
기본적으로 UITableViewCell의 selectionStyle 프로퍼티를 이용하여 파란색, 회색, 없음을 선택할 수 있습니다.
[cell setSelectionStyle:UITableViewCellSelectionStyleBlue]; // 파란색
[cell setSelectionStyle:UITableViewCellSelectionStyleGray]; // 회색
[cell setSelectionStyle:UITableViewCellSelectionStyleNone]; // 없음
음..그런데 뭔가 아쉽습니다. 다른색도 있었으면 좋을텐데 말이죠.
그래서 UITableViewCell에서는 Highlighted상태일 때에 setHighlighted:animation: 메소드가 호출됩니다.
* UITableViewCell Class Reference 참고
UITableViewCell을 상속받는 CustomTableViewCell을 만들어 setHighlighted:animation: 메소드를 오버라이딩하는 방법으로 배경색을 변경해 보도록 하겠습니다.
* 배경
- Xcode 4, iOS SDK 4.3
- 네비게이션
Step 1: 먼저 UITableViewCell을 상속받은 CustomTableViewCell을 생성합니다.
Step 2: setHighlighted:animation: 메소드 오버라이드
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
//배경이 보일 수 있게 배경위의 View들을 투명하게 처리
[self.contentView setBackgroundColor:[UIColor clearColor]];
[self.textLabel setBackgroundColor:[UIColor clearColor]];
}
return self;
}
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
{
[super setHighlighted:highlighted animated:animated];
// Highlighted - 빨간색
// Normal - 투명
[self setBackgroundColor:highlighted ? [UIColor redColor] : [UIColor clearColor]];
[self.textLabel setTextColor:highlighted ? [UIColor whiteColor] : [UIColor blackColor]];
}
적당한 위치에 위의 함수를 넣습니다.
Step 3: UITableView가 CustomTableViewCell을 사용하게 수정
//- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
- (void)configureCell:(CustomTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [[managedObject valueForKey:@"timeStamp"] description];
}
// Customize the appearance of table view cells.
- (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] autorelease];
}
*/
CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}// Configure the cell.
[self configureCell:cell atIndexPath:indexPath];
return (UITableViewCell *)cell;
}
Step 4: 확인
이제 빌드하고 실행하면 아래와 같이 빨간색이 나타나는 것을 확인할 수 있습니다.
* 예제소스 다운로드

TableViewCellHighlight.zip