2011-02-06 4 views
24

Мне нужно создать свой собственный UITableViewCell с помощью файла xib, чтобы нарисовать графический интерфейс ... Какие правильные шаги для создания моего нового класса и использования в моем UITableView?шаги ios для создания пользовательского UITableViewCell с xib-файлом

заранее спасибо

ответ

6

А video tutorial, показывающий, как сделать это с помощью Xcode 4.2 было сделано. Автор написал также blog post.

10

Лично я думаю, что оба предложенных учебника имеют большой недостаток, когда дело доходит до reuseIdentifier. Если вы забудете назначить его в построителе интерфейса или опечатать его, вы будете загружать нить каждый раз, когда вызывается cellForRowAtIndexPath.

Jeff LaMarche пишет об этом и как исправить это в этом blog post. Помимо reuseIdentifier он использует тот же подход, что и в документации на яблоко, на Loading Custom Table-View Cells From Nib Files.

После того, как прочитал все эти статьи, я придумал следующий код:

Edit: Если вы ориентируетесь IOS 5.0 и выше, вы хотите придерживаться Duane Fields' answer

@interface CustomCellWithXib : UITableViewCell 

+ (NSString *)reuseIdentifier; 
- (id)initWithOwner:(id)owner; 

@end 

@implementation CustomCellWithXib 

+ (UINib*)nib 
{ 
    // singleton implementation to get a UINib object 
    static dispatch_once_t pred = 0; 
    __strong static UINib* _sharedNibObject = nil; 
    dispatch_once(&pred, ^{ 
     _sharedNibObject = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil]; 
    }); 
    return _sharedNibObject; 
} 

- (NSString *)reuseIdentifier 
{ 
    return [[self class] reuseIdentifier]; 
} 

+ (NSString *)reuseIdentifier 
{ 
    // return any identifier you like, in this case the class name 
    return NSStringFromClass([self class]); 
} 

- (id)initWithOwner:(id)owner 
{ 
    return [[[[self class] nib] instantiateWithOwner:owner options:nil] objectAtIndex:0]; 
} 

@end 

UINib (доступный в iOS 4.0 и более поздних версиях) используется здесь как одноэлементный, поскольку, хотя используется reuseIdentifier, ячейка по-прежнему повторно инициализируется примерно 10 раз или около того. Теперь cellForRowAtIndexPath выглядит следующим образом:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CustomCellWithXib *cell = [tableView dequeueReusableCellWithIdentifier:[CustomCellWithXib reuseIdentifier]]; 
    if (cell == nil) { 
     cell = [[CustomCellWithXib alloc] initWithOwner:self]; 
    } 

    // do additional cell configuration 

    return cell; 
} 
+0

На мой взгляд, это лучший способ. Спасибо вам за это. Если бы это была моя тема, я бы назвал ее ответом. –

15

В iOS5 вы хотите использовать новый:

registerNib:forCellReuseIdentifier:

Что в основном делает то же самое ...

+0

Прохладный, не заметил этого. Благодаря! – christoph

+0

Это то, что я пытался запомнить! Ницца. – Ash

+1

В частности, добавьте это в свой viewDidLoad: [self.tableView registerNib: [UINib nibWithNibName: @ "CustomCell" bundle: nil] forCellReuseIdentifier: @ "CustomCell"]; –

0

Вы можете создать Класс CustomCell с XIB, который наследуется от UITableViewCell. Мы просто добавим категорию в файл .m-файла tableview следующим образом. Я думаю, что это самый простой метод, который применяется для создания пользовательских ячеек.

 

    @interface UITableViewCell(NIB) 
    @property(nonatomic,readwrite,copy) NSString *reuseIdentifier; 
    @end 
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    { 
     return 30; 
    } 

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
    static NSString *[email protected]"cell"; 
     CustomCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier]; 
     if(cell==nil) 
     { 
      NSLog(@"New Cell"); 
      NSArray *nib=[[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil]; 
      cell=[nib objectAtIndex:0]; 
      cell.reuseIdentifier=identifier; 

     }else{ 
      NSLog(@"Reuse Cell"); 
     } 
     cell.lbltitle.text=[NSString stringWithFormat:@"Level %d",indexPath.row]; 
     id num=[_arrslidervalues objectAtIndex:indexPath.row]; 
     cell.slider.value=[num floatValue]; 
     return cell; 
    } 
    @end 

1

`Вы можете создать пользовательские ячейки в виде таблицы с помощью файла .xib. Сначала настройте представление таблицы в контроллере представления, создайте новый файл xib с его классом и используйте его в виде таблицы.

- (IBAction)moveToSubCategory:(id)sender; 
@property (strong, nonatomic) IBOutlet UILabel *foodCategoryLabel; 
@property (strong, nonatomic) IBOutlet UIImageView *cellBg; 



-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [foodCatArray count]; 
} 



-(UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
     static NSString *simpleTableIdentifier = @"ExampleCell"; 
     ExampleCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 
     if (cell == nil) { 
     NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ExampleCell" owner:self options:nil]; 
     cell = [nib objectAtIndex:0]; 
    } 
    [cell setTag:indexPath.row]; 
    cell.cellBg.image=[UIImage imageNamed:[photoArray objectAtIndex:indexPath.row]]; 
    cell.foodCategoryLabel.text=[foodCatArray objectAtIndex:indexPath.row]; 
    return cell; 

} 
Смежные вопросы