본문 바로가기

iPhone

하나의 UIViewController 에서 두개 이상의 UITableView 를 표현하기


 2010/07/29 - [iPhone Dev] - APXML 를 사용 해 보세요. 

이전에 남겼던 포스팅을 보고 쪽지로 질문이 날라왔어요. 궁금하셨던 사항이 XML Parsing과 연관성이 있는 질문은 아니지만,  해결책이 간단한 Tip 이 될 수 있을 것 같아서 포스팅으로 남길께요.

UITableView 에 Data 를 바인딩 하기 위해서는 UITableViewDataSource 프로토콜을 구현해야 합니다.
정확히는, row 수와 각 row 마다 바인딩 될 데이터를 지정 해 주는 numberOfRowsInSection, cellForRowAtIndexPath 두 메서드를 구현하면 됩니다.

헌데, 만약 UIViewController 내에서 UITableView 를 하나가 아닌 두 개 이상이고 각 UITableView에 데이터를 바인딩 하려면 어떻게 해야 할까요?  (같은 UIViewController 내에서 UITableViewDataSource 프로토콜 내 함수를 구현하게 되면,  여러개의 UITableView 가 모두 같은 메서드를 호출하기 때문에 뜻하지 않은 결과를 얻으신 것 같더라고요.)

이런 경우에는,  UITableViewDataSource 프로토콜 내 함수에서 분기해서 처리하면 됩니다. 
분기할 때 방법은 두가지 정도가 있는데요. 
우선은 1. 각 테이블 뷰를 전역으로 가지고 있다가 메서드 인자 중 하나인 tableView 와 비교하는 것입니다. 
다른 방법으로는 2. 각 테이블 뷰를 생성할때 Tag 값을 주고, 마찬가지로 메서드 인자인 tableView 의 Tag 값을 확인하는 것이죠.
샘플 내에선 IB로 객체를 연결 했기 때문에 (전역으로 두고 사용) 1번 방법으로 코딩 되 있습니다.

[샘플]

Daum RSS 중 사회, IT 를 두 개의 테이블에 표시하는 간단한 샘플을 만들어 봤습니다.


[ UITableViewDataSource 내 메서드 에서 각 UITableView 분기하여 처리 ]

#pragma mark UITableView dataSource

// Customize the number of rows in the table view.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

if(tableView == societyTable) {

return [societyItems count];

} else if(tableView == digitalTable) {

return [digitalItems count];

}

else

return 0;

}



// 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];

    }

// Configure the cell.

if(tableView == societyTable) {

item* obj = (item *)[societyItems objectAtIndex:indexPath.row];

[[cell textLabel] setText:[obj title]];

} else if(tableView == digitalTable) {

item* obj = (item *)[digitalItems objectAtIndex:indexPath.row];

[[cell textLabel] setText:[obj title]];

}

    return cell;

}