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

iOS UITableViewCell 中 UIImageView 動態居中:自定義 Cell 或調整 imageView.frame 實現

     編輯:程式設計綜合問答

在 `UITableViewCell` 中讓 `imageView` 動態居中,不能直接對默認 `cell.imageView` 設置 frame (受系統佈局約束),需採用以下方案:

方案一:自定義 UITableViewCell (推薦、最可控)

  1. 創建 `CustomCell : UITableViewCell`,在 `initWithStyle:reuseIdentifier:` 中添加自己的 `UIImageView` 屬性,設置 `autoresizingMask` 或 Auto Layout 約束居中。
  2. 在 `tableView:cellForRowAtIndexPath:` 中複用自定義 Cell,直接賦值圖片。

方案二:調整系統 imageView.frame (快速嘗試,有局限)

UIImage *img = [UIImage imageNamed:@"friendsCelluserpic.png"];
cell.imageView.image = img;
// 關鍵:在 cell 佈局完成後 (layoutSubviews) 設置 frame 居中
// 或在 cellForRow 中強制計算 (需知 cell 寬高)
CGFloat imgW = img.size.width;
CGFloat imgH = img.size.height;
CGFloat cellW = cell.bounds.size.width; // 或 tableView.bounds.width
CGFloat cellH = cell.bounds.size.height;
cell.imageView.frame = CGRectMake((cellW - imgW) / 2, (cellH - imgH) / 2, imgW, imgH);
// 注意:cell.bounds 在此時可能尚未最終確定,建議在 cell 的 layoutSubviews 中設置

方案三:Auto Layout 约束 (iOS 8+)

// 在自定義 Cell 或 cell.contentView 中
UIImageView *imgView = cell.imageView;
imgView.translatesAutoresizingMaskIntoConstraints = NO;
[NSLayoutConstraint activateConstraints:@[
    [imgView.centerXAnchor constraintEqualToAnchor:cell.contentView.centerXAnchor],
    [imgView.centerYAnchor constraintEqualToAnchor:cell.contentView.centerYAnchor],
    [imgView.widthAnchor constraintEqualToConstant:imgW],
    [imgView.heightAnchor constraintEqualToConstant:imgH]
]];

避坑指南

  • 默認 `cell.imageView` 受 `contentView` 佈局邊距影響,直接設 frame 易被系統重置。
  • 異步加載圖片時,**必須在主線程更新 UI**,且處理 Cell 復用導致的圖片錯位 (SDWebImage/Kingfisher 內部已處理)。
  • 動態行高 (`UITableViewAutomaticDimension`) 時,圖片居中約束需與內容高度協同。

工程建議:**方案一 (自定義 Cell + Auto Layout) 為標準做法**,封裝復用邏輯,避免在 Controller 中操作 Cell 子視圖 frame。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved