본문 바로가기

Application Programming Interface/Cocoa

UITableView에 CustomTableViewCell 적용하기

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

UITableView에 CustomTableViewCell 적용하기

- by Tapito

 아래와 같이 TableViewCell이 표시되는 모양을 직접 만들어 UITableView에 띄워보도록 하겠습니다.


1. 데이터 구조체 작성하기

 먼저 사용자 구조체(여기서는 TapitoBusinessCard)를 작성합니다. 인명부 컨셉으로 간단하게 이름과 직장, 현재 재직 여부만을 저장하는 구조체입니다. Xcode를 열고 프로젝트를 하나 생성한 후 아래와 같이 구조체의 헤더 파일과 구현 파일을 작성합니다.

TapitoBusinessCard.h

#import <Foundation/foundation.h>

@interface TapitoBusinessCard : NSObject

// 이름, 직장, 재직 여부를 지정하여 TapitoBusinessCard 클래스 인스턴스를 초기화합니다.
+ (TapitoBusinessCard *) initWithName:(NSString *)nameValue andPlace:(NSString *)placeValue andWork:(BOOL)workValue;

// 이름을 가져오거나 설정합니다.
- (NSString *) name;
- (void) setName:(NSString *)nameValue;

// 직장을 가져오거나 설정합니다.
- (NSString *) place;
- (void) setPlace:(NSString *)placeValue;

// 재직 여부를 가져오거나 설정합니다. 값은 YES 또는 NO입니다.
- (BOOL) work;
- (void) setWork:(BOOL)workValue;

@end

TapitoBusinessCard.m

#import "TapitoBusinessCard.h"

@implementation TapitoBusinessCard
{
    NSString * name;
    NSString * place;
    BOOL work;
}

+ (TapitoBusinessCard *) initWithName:(NSString *)nameValue andPlace:(NSString *)placeValue andWork:(BOOL)workValue
{
    TapitoBusinessCard * result = [[TapitoBusinessCard alloc] init];
    
    result.name = nameValue;
    result.place = placeValue;
    result.work = workValue;
    
    return result;
}

- (NSString *) name
{
    return self->name;
}

- (void) setName:(NSString *)nameValue
{
    // nameValue가 nil이 아닐 때만 이름을 변경합니다.
    if (nameValue != nil) self->name = nameValue;
}

- (NSString *) place
{
    return self->place;
}

- (void) setPlace:(NSString *)placeValue
{
    // placeValue가 nil이 아닐 때만 직장을 변경합니다.
    if (placeValue != nil) self->place = placeValue;
}

- (BOOL) work
{
    return self->work;
}

- (void) setWork:(BOOL)workValue
{
    self->work = workValue;
}

@end

2. InterfaceBuilder로 커스텀 테이블 뷰 셀을 만들기

 위 구조체의 내용을 보여줄 커스텀 테이블 뷰 셀을 만듭니다. Main.storyboard를 열고 View에 UITableView를 넣습니다. UITableView 안에 UITableViewCell을 넣습니다. 아래와 같이 Prototype이라는 헤더가 붙으면서 빈 셀 하나가 만들어집니다.

 빈 셀에 이름(정확히 말하면 재사용 식별자)을 지정합니다. "Tapito Business Card Item" 정도로 지정하겠습니다.

 셀에 적당한 뷰들을 배치합니다.

 이 셀에 대한 코드를 만듭니다. [New File...]을 클릭하여 Cocoa Touch Class 파일을 생성합니다. 클래스 이름은 TapitoBusinessCardTableViewCell로 지정하겠습니다. 이 클래스를 위에서 만든 UI 셀에 연결시킨 다음 UI 셀에서 만든 각종 뷰들에 대한 outlet을 선언합니다.

TapitoBusinessCardTableViewCell.h

#import <UIKit/UIKit.h>

@interface TapitoBusinessCardTableViewCell
@property (strong, nonatomic) IBOutlet UILabel * labelName;
@property (strong, nonatomic) IBOutlet UILabel * labelPlace;
@property (strong, nonatomic) IBOutlet UISwitch * switchWork;
@end

3. View Controller에 UITableView가 작동되도록 코드 작성

 구조체의 내용을 보여 줄 셀은 작성되었습니다. 이제 이 셀이 보여질 TableView에 대한 설정을 합니다. 먼저 ViewController에서 UITableViewDataSource와 UITableViewDelegate 프로토콜을 사용하도록 지정합니다.

 테이블 뷰를 통해 보여줄 데이터가 보관된 구조체 배열을 mutableArray라고 하겠습니다. ViewController는 최소한 아래 3가지의 메서드를 구현해야 합니다.

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView;
표의 열 개수를 반환합니다. 여기에서는 1개 열만 보여질 것으므로 항상 1을 반환합니다.
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
section 번째 열에 대해 몇 개의 행이 존재하는지를 반환합니다. 매개변수 section은 열 번호로서 0부터 시작하는 양의 정수이며 numberOfSectionsInTableView가 반환하는 값보다는 작습니다. 여기에서는 section이 항상 0이므로 section = 0일 때 배열의 원소 수를 행 개수로서 반환합니다.
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
indexPath에서 행/열 번호가 전달되는데, 이 위치에 해당하는 셀을 구성하여 반환합니다.

View에 있는 UITableView의 dataSource와 delegate를 ViewController로 지정하면 끝났습니다.



시험하기

 ViewController.m의 viewDidLoad 메서드에 아래 구문을 추가합니다.

@implementation ViewController
{
    NSMutableArray * mutableArray;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    mutableArray = [[NSMutableArray alloc] init];
    
    [mutableArray addObject:[TapitoBusinessCard initWithName:@"Richard F. Baker" andPlace:@"Google" andWork:YES]];
    [mutableArray addObject:[TapitoBusinessCard initWithName:@"Sarah Schneider" andPlace:@"Facebook" andWork:NO]];
    [mutableArray addObject:[TapitoBusinessCard initWithName:@"Rachel Smith" andPlace:@"Apple" andWork:YES]];
    [mutableArray addObject:[TapitoBusinessCard initWithName:@"Susan Kim" andPlace:@"Samsung" andWork:NO]];
    [mutableArray addObject:[TapitoBusinessCard initWithName:@"Peter H. Yamasaki" andPlace:@"Sony" andWork:YES]];
}

// ... 후략 ...