Подтвердить что ты не робот

Ios для создания пользовательского UITableViewCell с xib файлом

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

заблаговременно

4b9b3361

Ответ 1

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

registerNib:forCellReuseIdentifier:

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

Ответ 2

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

Jeff LaMarche пишет об этом и как его исправить в этом сообщении в блоге. Помимо reuseIdentifier, он использует тот же подход, что и в документации Apple, на Загрузка пользовательских таблиц - Просмотр ячеек из файлов Nib.

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

Изменить: если вы ориентируетесь на iOS 5.0 и выше, вы захотите придерживаться ответа Duane Fields

@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;
}

Ответ 3

A видеоурок, показывающий, как сделать это с помощью Xcode 4.2. Автор написал сообщение .

Ответ 5

`Вы можете создавать пользовательские ячейки в виде таблицы с помощью файла .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;

}

Ответ 6

Вы можете создать класс 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