How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

后端 未结 16 2493
不思量自难忘°
不思量自难忘° 2020-11-27 10:27

I have a bunch of images I am using for cell\'s image views, they are all no bigger than 50x50. e.g. 40x50, 50x32, 20x37 .....

When I load the table view, the tex

16条回答
  •  粉色の甜心
    2020-11-27 10:51

    Here's how i did it. This technique takes care of moving the text and detail text labels appropriately to the left:

    @interface SizableImageCell : UITableViewCell {}
    @end
    @implementation SizableImageCell
    - (void)layoutSubviews {
        [super layoutSubviews];
    
        float desiredWidth = 80;
        float w=self.imageView.frame.size.width;
        if (w>desiredWidth) {
            float widthSub = w - desiredWidth;
            self.imageView.frame = CGRectMake(self.imageView.frame.origin.x,self.imageView.frame.origin.y,desiredWidth,self.imageView.frame.size.height);
            self.textLabel.frame = CGRectMake(self.textLabel.frame.origin.x-widthSub,self.textLabel.frame.origin.y,self.textLabel.frame.size.width+widthSub,self.textLabel.frame.size.height);
            self.detailTextLabel.frame = CGRectMake(self.detailTextLabel.frame.origin.x-widthSub,self.detailTextLabel.frame.origin.y,self.detailTextLabel.frame.size.width+widthSub,self.detailTextLabel.frame.size.height);
            self.imageView.contentMode = UIViewContentModeScaleAspectFit;
        }
    }
    @end
    
    ...
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *CellIdentifier = @"Cell";
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[SizableImageCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    
        cell.textLabel.text = ...
        cell.detailTextLabel.text = ...
        cell.imageView.image = ...
        return cell;
    }
    

提交回复
热议问题