위와 같은 테이블 뷰를 구성할 때 체크박스를 선택하는 기능을 구현해야 한다. 선택된 값을 저장하는 시점도 필요한데 언제가 되야 할지 처음엔 다소 어렵게 느껴질 수 있다. 하지만 tableView:cellForRowAtIndexPath: 델리게이트 메서드를 이용해서 간단히 구현 할 수 있다. 우선 다음 코드를 보자 일반적인 tableView:cellForRowAtIndexPath: 구현이다. 1. 재사용을 위해 cellIdentifier을 선언한다. static NSString *cellIdentifier = @"CELL"; 2. 만약 처음 cell을 생성해야 하는 경우는 if (cell == nil) 블럭 안에서 UITableViewCell이 생성 될 것이다. 나는 보통 셀이 생성될때 공통적인 속성을 설정한다. cell.selectionStyle을 설정한 것처럼 말이다. 3. 그 외 변동되는 부분은 아래의 코드에서 보듯이 cell의 객체가 nil이 아닐때 처리한다. static NSString *cellIdentifier = @"CELL"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease]; cell.selectionStyle = UITableViewCellSelectionStyleGray; } if ([[self.item objectForKey:@"select"] intValue] == indexPath.row) { cell.accessoryType = UITableViewCellAccessoryCheckmark; self.prevSelectedIndexPath = indexPath; } else { cell.accessoryType = UITableViewCellAccessoryNone; } cell.textLabel.text = [[self.item objectForKey:@"value"] objectAtIndex:indexPath.row]; return cell; 위의 코드대로라면 select row의 값만 UITableViewCellAccessoryCheckmark 가 표시될 것이다. 이제 tableView:didSelectRowAtIndexPath:를 구현하면 되는데 선택되 었을때 다음 코드와 같이 하면 선택된 셀이 변경될 것이다. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [self.item setValue:[NSNumber numberWithInt:indexPath.row] forKey:@"select"]; [tableView reloadData]; } 하지만 문제점이 있는데 바로 셀이 선택되는 순간 선택된 애니메이션이 보여지기도 전에 체크만되고 테이블 뷰가 리로드 될 것이다. 그래서 다음 코드를 적용하면 올바르게 동작할 것이다. 1. 미리 저장된 이전에 선택된 셀의 IndexPath와 선택된 셀의 IndexPath를 비교해 동일하다면 return한다. 2. 만약 같지 않다면 reloadRowsAtIndexPath:withAnimation: 메서드를 사용해서 이전에 선택된 셀 및 선택된 셀을 리로드한다. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSComparisonResult result = [self.prevSelectedIndexPath compare:indexPath]; if (result == NSOrderedSame) return; //셀렉트 저장 [self.item setValue:[NSNumber numberWithInt:indexPath.row] forKey:@"select"]; [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:self.prevSelectedIndexPath, indexPath, nil]withRowAnimation:UITableViewRowAnimationFade]; }
'영삼이의 IT정보' 카테고리의 다른 글
Remove @Override annotation (0) | 2012.06.26 |
---|---|
ios에서의 sqlite3 사용법 (0) | 2012.06.22 |
iOS 5에서 UIAlertView에 추가된 것 (0) | 2012.06.20 |
문자열 (NSString) 비교하기 (0) | 2012.06.20 |
날짜/시각 구하기 (0) | 2012.06.19 |