在 `UITableViewCell` 中讓 `imageView` 動態居中,不能直接對默認 `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 中設置
// 在自定義 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 + Auto Layout) 為標準做法**,封裝復用邏輯,避免在 Controller 中操作 Cell 子視圖 frame。