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

UITableView с двумя пользовательскими ячейками (несколько идентификаторов)

Я пытаюсь поместить ячейку в пространство между каждой ячейкой, которая будет скрыта установкой alpha = 0. В моей таблице ячейки пространства будут для нечетных строк.

Обратите внимание, что фактическая высота ячейки равна 85, но высота скрытой ячейки (т.е. пространство между ячейками) равна 20.

Проблема в том, что высота космической ячейки равна 85, но не 20, я не знаю почему. Возможно, ячейка загружена неправильно.

Cell вот UITableViewCell - фактическая ячейка - с идентификатором "Ячейка".

Cell2 - это пространство с идентификатором "Пространство".

Каждый класс выше имеет свой собственный класс UITableViewCell, и XIB файлы также назначаются каждому из них. Идентификатор также устанавливается в IB для каждого Xib.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier1 = @"Cell";
static NSString *CellIdentifier2 = @"Space";

Cell *cell = (Cell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];

if(!cell)
{
    NSArray *ar = [[NSBundle mainBundle] loadNibNamed:@"CellView" owner:nil options:nil];
    for (id obj in ar)
    {
        if ([obj isKindOfClass:[Cell class]])
        {
            cell = (Cell *)obj;
            break;
        }
    }
}

if (indexPath.row % 2 == 1)
{
    Cell2 *cell2 = (Cell2 *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];

    if (!cell2)
    {
        NSArray *ar = [[NSBundle mainBundle] loadNibNamed:@"Cell2" owner:nil options:nil];
        for(id obj in ar)
        {
            if([obj isKindOfClass:[Cell2 class]])
            {
                cell2 = (Cell2 *)obj;
                break;
            }
        }

        // Method 1
        cell2 = [[Cell2 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2];
         // Method 2
        //cell2 = [[Cell2 alloc] init];
        // Method 3
        //cell2 = (Cell2 *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];

        [cell2.contentView setAlpha:0];
        // prevent selection and other stuff
        [cell2 setUserInteractionEnabled:NO];
    }
    return cell2;
}
else
{
    // Configure the actual cell
}


return cell;

}

4b9b3361

Ответ 1

* Я переименовал некоторые из ваших имен NIB/Class для лучшего понимания. *

Сначала вы должны зарегистрировать NIB каждой ячейки:

- (void)viewDidLoad{
    [super viewDidLoad];

    static NSString *CellIdentifier1 = @"ContentCell";
    static NSString *CellIdentifier2 = @"SpaceCell";

    UINib *nib = [UINib nibWithNibName:@"CellViewNIBName" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:CellIdentifier1];

    nib = [UINib nibWithNibName:@"CellSpaceNIBName" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:CellIdentifier2];

    self.contentView.hidden = YES;
    [self loadData];
}

Поскольку у вас зарегистрировано NIB, dequeueReusableCellWithIdentifier: всегда будет возвращать ячейку:

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath      *)indexPath
{
    static NSString *CellIdentifier1 = @"ContentCell";
    static NSString *CellIdentifier2 = @"SpaceCell";

    // Space Cell
    if (indexPath.row % 2 == 1) {
        CellSpace *cell = (CellSpace *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
        return cell;
    }

    // Content cell
    else {
        CellView *cell = (CellView *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
        // Configure cell
        return cell;
    }
}

И последнее, но не менее важное: убедитесь, что реализован следующий метод делегата:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Space cell height
    if (indexPath.row % 2 == 1) {
        return 20.0f;
    }

    // Content cell height
    else {
        return 80.0f;
    }
}

Ответ 2

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *returncell;

    static NSString *cellIdentifier ;
    if(indexPath.section == 0)
    {
        cellIdentifier = @"cell1";
    }
    else if (indexPath.section == 1)
    {
        cellIdentifier = @"cell2";
    }
    UITableViewCell *myCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    MapTableViewCell *myCustomCell = (MapTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(indexPath.section == 0)
    {
        if(myCell == nil)
        {
            myCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            getLocationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            getLocationBtn.frame = CGRectMake(myCell.frame.origin.x,myCell.frame.origin.y+5 , 200, 30);
            [getLocationBtn setTitle:@"your button title" forState:UIControlStateNormal];
            [getLocationBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
            [getLocationBtn addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];

        }

        [myCell.contentView addSubview:getLocationBtn];
        returncell = myCell;
    }
    else if (indexPath.section == 1)
    {
        if (myCustomCell == nil)
        {
            myCustomCell = [[MapTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }

        myCustomCell.nearbyLocation.text = @"demo Text";
        returncell = myCustomCell;
    }

    return returncell;
}

//mycustom tablviewcell

импорт "MapTableViewCell.h"

@implementation MapTableViewCell

@synthesize nearbyLocation;

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self)
    {    
        self.backgroundColor = [UIColor groupTableViewBackgroundColor];
        nearbyLocation = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, 200, 30)];

        [self addSubview:nearbyLocation];
    }

    return self;
}
@end

Лучший способ использовать количество настраиваемых ячеек с ячейкой по умолчанию

Ответ 3

В дополнение к предоставленным ответам я хочу подчеркнуть, что Идентификатор ячейки для каждой отдельной пользовательской ячейки также должен быть разным.

Например, пользовательский cellA с идентификатором "Cell" и пользовательским cellB с идентификатором "Cell2".