在UITableViewCell中自动调整掩码

时间:2012-10-26 20:28:49

标签: objective-c ios uitableview autoresize

我正在创建一个具有以下屏幕的应用。但是,我不能按照我的意愿将图像排成一行。我想要的是图像尽可能大,不会被扭曲,没有它们覆盖文本或泄漏到单元格之外。我想我的代码正确缩小了图像;但是,我无法弄清楚要放在它们上的自动调整遮罩。

enter image description here

以下是相关代码:

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Prototype Cell"];
    if(!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Prototype Cell"];
    }
    Restaurant *restaurantForIndex = [self.restaurants objectAtIndex:indexPath.row];
    UILabel *label = [[UILabel alloc] init];
    label.backgroundColor = [UIColor greenColor];
    label.text = restaurantForIndex.name;
    label.font = [UIFont fontWithName:CELL_FONT_NAME size:CELL_FONT_SIZE];
    [cell.contentView addSubview:label];

    cell.backgroundColor = [UIColor whiteColor];

    UIImage *image = [restaurantForIndex getLogo];
    if(image.size.height > CELL_HEIGHT - 2 *CELL_Y_BUFFER)
    {
        float scale = (CELL_HEIGHT - 2 * CELL_Y_BUFFER) / image.size.height;
        image = [UIImage scaleImage:image toSize:CGSizeMake(image.size.width * scale, CELL_HEIGHT - 2 * CELL_Y_BUFFER)];
    }
    float textWidth = [label.text sizeWithFont:[UIFont fontWithName:CELL_FONT_NAME size:CELL_FONT_SIZE]].width;
    label.frame = CGRectMake(CELL_X_BUFFER, CELL_Y_BUFFER, textWidth, cell.contentView.frame.size.height - 2 * CELL_Y_BUFFER);
    label.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    if(label.frame.origin.x + textWidth + NAME_LOGO_BUFFER + image.size.width + CELL_X_BUFFER > cell.contentView.frame.size.width)
    {
        float newImageWidth = cell.contentView.frame.size.width - (label.frame.origin.x + textWidth + NAME_LOGO_BUFFER + CELL_X_BUFFER);
        float scale = newImageWidth / image.size.width;
        image = [UIImage scaleImage:image toSize:CGSizeMake(newImageWidth, image.size.height * scale)];
    }
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    float xOrigin = cell.contentView.frame.size.width - image.size.width - CELL_X_BUFFER;
    float yOrigin = (cell.contentView.frame.size.height - image.size.height) / 2 ;
    float width = image.size.width;
    float height = image.size.height;
    imageView.frame = CGRectMake(xOrigin, yOrigin, width, height);

    //IMPORTANT LINE OF CODE HERE
    imageView.autoresizingMask =  UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin  | UIViewAutoresizingFlexibleLeftMargin;
    [cell.contentView addSubview:imageView];
    return cell;
}

关于代码的一些注意事项:在哪里看到大写的BUFFER字,它只是一个常量,因此子视图不会触及单元格的边缘。

0 个答案:

没有答案