Динамическое изменение размера ширины UIImage в ячейке UITableView в XCode - PullRequest
0 голосов
/ 25 мая 2010

Я использую код ниже, чтобы собрать свой UITableView. Высота ячейки позволяет отображать первые три строки в таблице без прокрутки. Все хорошо с этими первыми тремя рядами. Но как только я прокручиваю исходные первые три строки, изображение в myImage наследует ширину ячеек в первых трех строках и не изменяет размер в соответствии со значением, извлеченным из массива на основе indexPath.row.

Ячейка, очевидно, используется повторно из оператора else из первоначально нарисованных ячеек, но мне нужно найти способ, позволяющий изменять ширину myImage для каждой строки.

Любая помощь высоко ценится! LQ

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

const NSInteger LABEL_TAG = 1001;
const NSInteger IMAGE_TAG = 1002;

UILabel *myLabel;
UIImageView *myImage;

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [myTableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

    // Create the cell

    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero
                        reuseIdentifier:CellIdentifier]
                        autorelease];

    // Constant values

    const CGFloat LABEL_HEIGHT = 20;
    const CGFloat LABEL_WIDTH = 140;
    const CGFloat LABEL_INDENT = 1;
    const CGFloat LABEL_TOP = 0.065 * myTableView.rowHeight;

    // Create the label;

    myLabel = [[[UILabel alloc] initWithFrame:
            CGRectMake(
                LABEL_INDENT,
                LABEL_TOP  + LABEL_HEIGHT,
                LABEL_WIDTH,
                LABEL_HEIGHT)]
            autorelease];

    [cell.contentView addSubview:myLabel];

    // Configure the label

    myLabel.tag = LABEL_TAG;
    myLabel.backgroundColor = [UIColor clearColor];
    myLabel.textColor = [UIColor blueColor];
    myLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize] - 3];
    myLabel.textAlignment = UITextAlignmentRight;

    // Create the image (NOTE: THIS IS THE PROBLEMATIC PART)

    // Extract the width for the image based on an array value for each row:

    int xValue = [[myArray objectAtIndex:(indexPath.row)]intValue]; 
    float xLength = (float)xValue / 100;

    myImage = [[[UIImageView  alloc] initWithFrame:
                CGRectMake(
                    LABEL_INDENT + 53,              // This places the image to the right of the label
                    LABEL_TOP  + LABEL_HEIGHT,
                    xLength * LABEL_WIDTH,          

// Здесь настраивается ширина каждой строки LABEL_HEIGHT] autorelease];

    [cell.contentView addSubview:myImage];

    myImage.contentMode = UIViewContentModeLeft;
    myImage.image = [UIImage imageNamed:@"ProgressBar.png"];
    myImage.clipsToBounds = YES;

} else {

    // Re-use cells

    myLabel = (UILabel *)[cell viewWithTag:LABEL_TAG];
    myImage = (UIImageView *)[cell viewWithTag:IMAGE_TAG];  
}

return cell;

}

1 Ответ

1 голос
/ 26 мая 2010

Выше используются ячейки, на которые вы обращаете внимание в своих комментариях, но; после нахождения кэшированной ячейки вы снова выполняете настройку, независимо от того, старая ячейка или новая.

UITableViewCell - это «двухчастный», при первой ссылке на ячейку она создается и создается, все последующие обращения к ней следует только обновлять. (на ячейку ссылаются каждый раз, когда она прокручивается на экран или перезагружается представление таблицы и т. д., это часто происходит, поэтому для экономии времени ЦП также лучше не выполнять одни и те же настройки снова и снова).

Итак, попробуйте подойти к этому так:

- (void) configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {

    UILabel *settingText = [ISInterfaceElement getLabel:Headline]; //Opps... ISInterfaceElement is my custom class. All it does is return a UILabel with settings that comply for a Headline label, according to an enum in the header.
    [settingText setFrame:CGRectMake(0.0f, 15.0f, 320.0f, 20.0f)];
    [settingText setTextAlignment:UITextAlignmentCenter];
    [settingText setTag:SETTINGS_LABEL];
[cell addSubview:settingText];
    UIView *background = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 50.0f)];
    [cell addSubView:background]; //added
    [background release]; //added

[cell setSelectionStyle:UITableViewCellSelectionStyleNone];     
}

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {       
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        [self configureCell:cell atIndexPath:indexPath];
    }


    [(UILabel*)[cell viewWithTag:SETTINGS_LABEL] setText:@"Settings…"];

    return cell;
}

Поэтому cellForRowAtIndexPath вызывает метод configureCell, если ему требуется новая настройка ячейки, иначе он просто обновляет ячейку с правильным значением из модели (обычно [someArray objectAtIndex: indexPath.row], но в моем случае просто строка.

Итак, отправьте по любому параметру (высоте), который вам нужен метод configureCell, чтобы знать, как создать ячейку, и выполнить все построения в этом методе и все обновления в cellForRowAtIndex.

Надеюсь, это имеет смысл:)

...