콘텐츠로 건너뛰기
Home » tableview 셀 생성

tableview 셀 생성

테이블 뷰의 데이터소스 프로토콜에는 -tableView:cellForRowAtIndexPath: 라는 메소드가 있다. 이 메소드는 테이블 뷰 상의 특정 위치에 들어갈 cell 객체를 알려주는 메소드로 프로그래머가 작성해주어야 하는 부분이다. 일반적으로는 이렇게 작성했다.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    const NSString *reuseID = @"cell";
    UITableViewCell *cell = [tableView dequeReusableCellWithIdentifier:reuseID];
    if (cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseID];
    }
    ...
    return cell;
}


즉 캐시되어 있는 셀 객체가 없으면 nil 이 리턴되고 그렇다면 수동으로 cell 객체를 만들어줘야했다. iOS6 부터는 이와 조금 다른 -dequeReusableCellWithIdentifier:atIndexPath:라는 메소드가 추가되었는데, 이 메소드는 항상 유효한 셀 객체를 리턴한다. 즉 캐시된 셀이 없으면 기본 스타일의 셀을 새롭게 만들어주는 것이다.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    const NSString *reuseID = @"cell";
    UITableViewCell *cell = [tableView dequeReusableCellWithIdentifier:reuseID atIndexPath:indexPath];
    ...
    return cell;
}

만약 별도로 서블 클래싱한 셀을 쓰고 싶다면, 뷰 컨트롤러의 -viewDidLoad에서 registerClass:forReuseIdentifier:를 통해서 등록해주면 된다.

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.tableView registerClass:[MyNewCell class] forReuseIdentifier:@"cell"];
}