Как создать настроенный сгруппированный UITableView с использованием изображений - PullRequest
2 голосов
/ 28 декабря 2011

Я хотел бы реализовать надежную систему для создания настраиваемого сгруппированного табличного представления, например, приложение ConvertBot, которое использует настраиваемые стили для таблиц.

http://i.stack.imgur.com/geAuw.png

Я бы получил тот же эффект, используя фоновые изображения для вставки в backgroundView ячеек, это код, который я использую.

Используемый код

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

UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];      

    cell.textLabel.text = [NSString stringWithFormat:@"Cell Name %d %d",indexPath.row,indexPath.section];
    cell.textLabel.backgroundColor = [UIColor clearColor];

    //
    // Create a custom background image view.
    //        
    cell.backgroundView =
    [[[UIImageView alloc] init] autorelease];
    cell.selectedBackgroundView =
    [[[UIImageView alloc] init] autorelease];
    UIImage *rowBackground;
    UIImage *selectionBackground;
    NSInteger sectionRows = [self.tableView numberOfRowsInSection:[indexPath section]];
    NSInteger row = [indexPath row];
    if (row == 0 && row == sectionRows - 1)
    {
        rowBackground = [[UIImage imageNamed:@"TableSingleBackground.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
        selectionBackground = [[UIImage imageNamed:@"TableSingleBackgroundSelected.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];

    }
    else if (row == 0)
    {
        rowBackground = [[UIImage imageNamed:@"TableTopBackground.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 1, 10)];
        selectionBackground = [[UIImage imageNamed:@"TableTopBackgroundSelected.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 1, 10)];
    }
    else if (row == sectionRows - 1)
    {
        rowBackground = [[UIImage imageNamed:@"TableBottomBackground.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(1, 10, 10, 10)];
        selectionBackground = [[UIImage imageNamed:@"TableBottomBackgroundSelected.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(1, 10, 10, 10)];
    }
    else
    {
        rowBackground = [[UIImage imageNamed:@"TableMiddleBackground.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(1, 10, 1, 10)];
        selectionBackground = [[UIImage imageNamed:@"TableMiddleBackgroundSelected.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(1, 10, 1, 10)];
    }
    ((UIImageView *)cell.backgroundView).image = rowBackground;
    ((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;


    UIImage *indicatorImage = [UIImage imageNamed:@"DetailDisclosure.png"];
    cell.accessoryView =
    [[[UIImageView alloc]
      initWithImage:indicatorImage]
     autorelease];

}


return cell;  
}

Это результат:

http://i.stack.imgur.com/EmwX7.png

Вы видите, что первая ячейка ненарисовано правильно.Эта прокрутка вызвала быстрая прокрутка. Как избежать этой проблемы?Я хотел бы знать, есть ли более эффективное решение, которое не влияет на производительность и его легко внедрить, например, настраиваемый UITableViewCell или что-то подобное.

Любое предложение?

1 Ответ

5 голосов
/ 29 декабря 2011

Вы создаете новые ячейки только тогда, когда tableView не использует ячейку, которая уже была создана.То, что вы видите, - это повторно используемая ячейка, которая была в «средней» позиции, когда она была создана, но теперь она повторно используется в «верхней» позиции без установки нового изображения.

Я бы предложил использовать несколько идентификаторов, по одному для каждой ситуации (один, верх, середина, низ):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath     *)indexPath
{
    static NSString *singleIdentifier   = @"SingleCell";
    static NSString *topIdentifier      = @"TopCell";
    static NSString *middleIdentifier   = @"MiddleCell";
    static NSString *bottomIdentifier   = @"BottomCell";

    NSString *CellIdentifier = nil;
    NSInteger sectionRows = [tableView numberOfRowsInSection:[indexPath section]];
    NSInteger row = [indexPath row];

    // Select the identifier

    if (row == 0 && row == sectionRows - 1)
    {
        CellIdentifier = singleIdentifier;        
    }
    else if (row == 0)
    {
        CellIdentifier = topIdentifier;
    }
    else if (row == sectionRows - 1)
    {
        CellIdentifier = bottomIdentifier;
    }
    else
    {
        CellIdentifier = middleIdentifier;
    }

    UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];      

        cell.textLabel.text = [NSString stringWithFormat:@"Cell Name %d %d",indexPath.row,indexPath.section];
        cell.textLabel.backgroundColor = [UIColor clearColor];

        //
        // Create a custom background image view.
        //        
        cell.backgroundView =
        [[[UIImageView alloc] init] autorelease];
        cell.selectedBackgroundView =
        [[[UIImageView alloc] init] autorelease];
        UIImage *rowBackground;
        UIImage *selectionBackground;
        NSInteger sectionRows = [self.tableView numberOfRowsInSection:[indexPath section]];
        NSInteger row = [indexPath row];
        if (row == 0 && row == sectionRows - 1)
        {
            rowBackground = [[UIImage imageNamed:@"TableSingleBackground.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
            selectionBackground = [[UIImage imageNamed:@"TableSingleBackgroundSelected.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];

        }
        else if (row == 0)
        {
            rowBackground = [[UIImage imageNamed:@"TableTopBackground.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 1, 10)];
            selectionBackground = [[UIImage imageNamed:@"TableTopBackgroundSelected.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 1, 10)];
        }
        else if (row == sectionRows - 1)
        {
            rowBackground = [[UIImage imageNamed:@"TableBottomBackground.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(1, 10, 10, 10)];
            selectionBackground = [[UIImage imageNamed:@"TableBottomBackgroundSelected.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(1, 10, 10, 10)];
        }
        else
        {
            rowBackground = [[UIImage imageNamed:@"TableMiddleBackground.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(1, 10, 1, 10)];
            selectionBackground = [[UIImage imageNamed:@"TableMiddleBackgroundSelected.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(1, 10, 1, 10)];
        }
        ((UIImageView *)cell.backgroundView).image = rowBackground;
        ((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;


        UIImage *indicatorImage = [UIImage imageNamed:@"DetailDisclosure.png"];
        cell.accessoryView =
        [[[UIImageView alloc]
          initWithImage:indicatorImage]
         autorelease];

    }


    return cell;  
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...