我正在创建一个具有以下屏幕的应用程序。但是,我无法让图像按照我的意愿排列。我想要的是图像尽可能大,不会失真,也不会覆盖文本或泄漏到单元格之外。我认为我的代码可以正确缩小图像;但是,我不知道要给它们戴上什么自动调整大小的蒙版。
以下是相关代码:
- (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 单词,它都是一个常量,因此子视图不会触及单元格的边缘。