Динамически созданные подпредставления в подклассе UITableViewCell - PullRequest
0 голосов
/ 24 августа 2011

У меня есть собственный класс UITableViewCell, и я хочу отображать изображения и строки линейно. Например:

Строка 1: [Изображение1] строка1 [Изображение2] строка2 [Изображение3]

Строка 2: [Image4] string3 [Image5]

Изображения имеют различную ширину, но я хотел бы иметь одинаковый интервал. Как бы я это сделал? Я пытался манипулировать подпредставлениями и CGRectMake безрезультатно.

Кроме того, я использую NSDictionary для хранения содержимого, и число изображений / строк не является постоянным для каждой ячейки.

Мой CustomCell класс:

#import "CustomCell.h"


@implementation CustomCell

@synthesize primaryLabel,secondaryLabel,image1;


-  (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
        // Initialization code
        primaryLabel = [[UILabel alloc]init];
        primaryLabel.textAlignment = UITextAlignmentLeft;
        primaryLabel.font = [UIFont systemFontOfSize:16];
        secondaryLabel = [[UILabel alloc]init];
        secondaryLabel.textAlignment = UITextAlignmentLeft;
        secondaryLabel.font = [UIFont systemFontOfSize:14];
        image1 = [[UIImageView alloc]init];

        [self.contentView addSubview:primaryLabel];
        [self.contentView addSubview:secondaryLabel];
        [self.contentView addSubview:image1];

    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    CGRect frame;
    frame= CGRectMake(0 ,5, 200, 25);
    primaryLabel.frame = frame;

    frame= CGRectMake(0 ,30, 200, 25);
    secondaryLabel.frame = frame;

    frame= CGRectMake(0, 60, 23, 20);
    image1.frame = frame;

...

Мой RootViewController

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

    static NSString *CellIdentifier = @"Cell";

    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    // Set up the cell...
    NSDictionary *dictionary = nil;


//Search
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        dictionary = [self.filteredListContent objectAtIndex:indexPath.row];
    }
    else
    {
        dictionary = [self.tableDataSource objectAtIndex:indexPath.row];
    }


//Original
    cell.primaryLabel.text = [dictionary objectForKey:@"Title"];    


    for (NSArray *keystroke in [dictionary objectForKey:@"Strokes"]) {


           for (int i = 0; i < 2; i++) {


               if ([(NSString *)keystroke isEqualToString:@"string1"] || [(NSString *)keystroke isEqualToString:@"string2"]) {
                 cell.secondaryLabel.text = (NSString *)keystroke; 
                 }

               else { 
            NSString *imageFilePath = [NSString stringWithFormat:@"%@.png", keystroke];
            NSLog(@"%@", imageFilePath);
            UIImage *myimage = [UIImage imageNamed:imageFilePath];

                cell.image1.image = myimage;

        }
        }
    }
    return cell;


}

...

Очевидно, здесь много дыр. Прежде всего, когда я перебираю свой словарь, мне нужно переместить мое подпредставление CustomCell вправо, чтобы я мог разместить изображения / текст рядом с предыдущим подпредставлением.

1 Ответ

0 голосов
/ 24 августа 2011

Вы на правильном пути. В вашем подклассе UITableViewCell вам потребуется переопределить layoutSubviews, определить CGRects для каждого UIImageView или UILabel вручную и установить их в качестве фрейма соответствующего вида.

Проверьте CGRectGetMaxX . Это будет очень полезно в этом контексте.

...