首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UITableViewCell 顯示圖片原始尺寸:手動建立 UIImageView 並設定 frame

     編輯:程式設計綜合問答

在 cellForRowAtIndexPath 中手動建立 UIImageView,以圖片實際尺寸設定 frame,避免 Cell 自動縮放導致變形。

程式碼

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    NSData *imageData = ...; // 取得圖片資料
    UIImage *image = [UIImage imageWithData:imageData];
    if (image) {
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(2, 8, image.size.width, image.size.height)];
        imgView.image = image;
        [cell.contentView addSubview:imgView];
    }
    return cell;
}

關鍵點

  • 使用 image.size.width/height 作為 frame 尺寸,保持原始比例。
  • 加入 cell.contentView 而非直接加入 cell。
  • 若需重用,建議在 Cell 子類中建立 UIImageView 屬性,複用時只更新 image 與 frame。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved