iOS 調整UITableViewCell中的imageView 的圖片大小

當我們在iOS中實現帶圖片帶列表顯示時UITableViewCell中自帶了一個存放圖片的控件UIImageView,當我們獲取的圖片大小一致時,圖片能夠很整齊大顯示,可是有些時候我們獲取的列表圖片的大小並不完全一致,爲了保證界面的美觀我們必須調整圖片大小或位置,可是當我們在定義好的UITableViewCell對象中設置cell.imageView.bounds、cell.imageView.frame時發現無論設置什麼值都無法改變圖片的大小和位置。

解決辦法一:

 給UITableViewCell的成員設置框架屬性後不起作用,解決辦法是在UITableViewCell的子類中重寫layoutSubviews,在其中改變一些屬性的值。

重定義一個uitableviewcell,它自動生成的代碼不需要動,只要在.m文件中再加上下面的代碼即可:

- (void)layoutSubviews {

    [superlayoutSubviews];

    self.imageView.bounds =CGRectMake(0,0,44,44);

    self.imageView.frame =CGRectMake(0,0,44,44);

    self.imageView.contentMode =UIViewContentModeScaleAspectFit;

    

    CGRect tmpFrame = self.textLabel.frame;

    tmpFrame.origin.x = 46;

    self.textLabel.frame = tmpFrame;

    

    tmpFrame = self.detailTextLabel.frame;

    tmpFrame.origin.x = 46;

    self.detailTextLabel.frame = tmpFrame;    

}

解決辦法二:

 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 [...]
        
//1、首先對image付值
cell.imageView.image=[UIImage imageNamed:@"default_image"];
//2、調整大小
      CGSize itemSize = CGSizeMake(40, 40);
      UIGraphicsBeginImageContextWithOptions(itemSize, NO, UIScreen.mainScreen.scale);
      CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
      [cell.imageView.image drawInRect:imageRect];
      cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();

 [...]
     return cell;
}

很開心。。。完美解決

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章