IB를 이용해서 Custom UITableViewCell 만들기 :: 2009/11/25 18:24
UITableViewCell을 Inteface Builder(이하 IB)를 사용해서 만들어 보려고 합니다. 그런데 개발툴에는 IB에서 UITableViewCell을 기준으로 xib파일을 생성할 수 없기 때문에 UIViewController를 생성해서 이것을 활용하려고 합니다.
먼저 원리를 살펴보자면 UIViewController에는 UIView를 기본으로 가지는 xib을 생성할 수 있습니다. 그래서 view로 연결되는데 전 여기서 view를 UIView를 사용하는 것이 아니라 UITableViewCell을 사용하려고 합니다.
UITableViewCell도 UIView를 상속한 클래스이기 때문에 UIViewController에서 view로 IBOutlet으로 연결할 수 있기 때문입니다.
그런다음에 소스에서는 UIViewController initWithNibName:bundle: 메소드를 이용해서 만든 xib파일을 로드해서 view를 호출해서 CustomTableViewCell로 형변환을 시켜서 반환시키면 됩니다.
쉽게 이해되지 않을 것입니다. 그러면 소스와 함께 보도록 하겠습니다.
먼저 새로운 파일 만들기를 해서 User Interface에서 View XIB로 customCell.xib를 생성합니다.
그런 다음에 File's Owner는 UIViewController로 바꿔주고,

view는 제거하고 Library에서 UITableViewCell을 끌어서 창에 넣어서 다음과 같이 만듭니다.

여기서 File's Owner인 UIViewController의 view로 Table View Cell을 연결해 줍니다.

그리고 다음과 같이 CustomCell 클래스를 만들어 줍니다.
#import <UIKit/UIKit.h>
#define CustomCellIdentifier @"CustomCellIdentifier"
@interface CustomCell : UITableViewCell {
}
+ (id)cellWithNib; ///< 이를 통해서 CustomCell을 반환하게 할 것입니다.
@end
@implementation CustomCell
+ (id)cellWithNib
{
AlbumListCell *cell;
UIViewController *controller = [[UIViewController alloc] initWithNibName:@"CustomCell" bundle:nil];
cell = (AlbumListCell *)controller.view;
[controller release];
return cell;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)dealloc {
[super dealloc];
}
@end
그리고 xib에 다음과 같이 identifier를 추가해 줍니다.

그리고 이 클래스가 CustomCell클래스를 사용한다고 것을 연결해주는 것을 잊으면 안됩니다.

이제 기본적으로 IB를 사용해서 기본적인 UITableViewCell을 만들었습니다.
이를 호출하려면 다음과 같이 호출해 주면 됩니다.
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = (CustomCell *)[aTableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
if(cell == nil) {
cell = [CustomCell cellWithNib];
}
...
return cell;
}
나머지는 동일하게 해주면 됩니다.
그리고 만약 Cell에 배경을 주려면 IB에서 UITableViewCell의 속성중에서 backgroundView에 연결시켜주면되고, 선택할 때 눌려지는 효과의 이미지를 추가하려면 selectedBackgroundView와 연결시켜주면 됩니다.
그럼 오늘도 즐코딩하세요. ^^
Trackback Address :: http://zemy.net/tc/zemyblue/trackback/190


