영삼이의 IT정보2012. 6. 21. 10:23


위와 같은 테이블 뷰를 구성할 때 체크박스를 선택하는 기능을 구현해야 한다. 선택된 값을 저장하는 시점도 필요한데 언제가 되야 할지 처음엔 다소 어렵게 느껴질 수 있다. 하지만 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 allocinitWithStyle: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.rowforKey:@"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 == NSOrderedSamereturn;

    

    //셀렉트 저장

    [self.item setValue:[NSNumber numberWithInt:indexPath.rowforKey:@"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
Posted by 다오나무
iOS2012. 6. 20. 19:07

일반적인 경우라면 iOS에서 기본적으로 제공하는 Cell Type을 통해 구현이 가능하지만, 특별히 사용자가 디자인한데로 cell을 만들어 사용하는 방법도 있다. Interface Builder를 통해 cell xib를 만들어 customize 한 cell을 만들어 보자.

1. 프로젝트를 생성하고 "UITableViewCell" 을 상속받은 Objective-C 클래스를 생성한다.



2. Custom Cell을 꾸밀 xib파일을 생성한다.(일반적으로 objective-c 클래스 파일 이름과 xib이름을 동일하게 - CustomCell이라고 - 만든다)

3. xib파일을 열어 우측 하단의 library에서 "Table View Cell"을 끌어다 놓는다. 끌어다 놓은 Table View Cell을 선택하고"Identity Inspector" 창에서 Custom Class를 위에서 만든 Objective-c Class인 "CustomCell"로 지정한다.

 4. xib에 구성하고 싶은 UI들을 올려놓고 "CustomCell class"에서 IBOutlet을 이용하여 UI component들과 연결을 한다.
 
5. TableView를 사용하기 위한 기본설정을 한다. 기본적인 내용은 여기에서 확인하면 된다.

6. ViewController.h에 TableView에 넣을 NSArray형태의 데이터를 @property로 선언하고 @synthesize로 선언한다.
 //ViewController.h
@property (retainNSMutableArray *products;
//ViewController.m
@synthesize products; 
 
 
7. 테이블에 들어갈 내용이 상품정보임으로 상품정보를 가지고 있을 Objective-C클래스(domain object)를 만든다.(이름은 Product라는 이름으로 만든다.)
 
 
8. CustomCell에 Product를 넘기면 Product의 property값을 CustomCell에 set해주는 method를 만들어 준다.

9. TableView 사용시 구현해야할 delegate method들을 구현한다.
 

 [실행 결과]

Posted by 다오나무