如何讓 UITableViewCell 中的 imageView 大小固定,cell.imageview大小
UITableView
可以算是使用頻率最高的組件之一的,在開發過程中經常需要展示一些簡單的資訊列表
常見列表布局
,很多頁面其實就是這種展示結果,通常需要imageView
,textLabel
,detailTextlabel
,而UITableViewCell
本身提供了方便的自動布局(當有圖片和沒圖片時,textLabel和detailLabel的位置會左右自動調整). 但是圖片的大小卻是沒有辦法固定的(直接設定imageView.frame
是無法固定imageView
的大小的),那麼一般來說解決這個問題的辦法有兩種:
- 固定顯示圖片的大小(包括PlaceHolder)
- 自訂tableViewCell,添加自訂的
imageView
,textLabel
和detailTextLabel
這兩種方式都可以解決這個問題,但是這兩種方式其實都挺麻煩的,能否直接固定imageView的大小呢? 方法是有的,只需要重載layoutSubviews
即可
派生UITableViewCell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
//自訂一個Cell @interface MMCell : UITableViewCell
@end
@implementation MMCell
//重載layoutSubviews - (void)layoutSubviews { UIImage *img = self.imageView.image; self.imageView.image = [UIImage imageName:@"res/PlaceHolder.png"]; [super layoutSubviews]; self.imageView.image = img; }
@end
|
這樣,我們只要使用MMCell
就可以固定imageView
的大小了,且大小為PlaceHolder.png
的大小(一般來說這種頁面都會使用一個PlaceHolder.png
來顯示預設圖片).
原理是在UItableVeiw
的layoutSubviews
調用時,會根據imageView.image
的大小來調整imageView
,textLabel
,detailTextLabel
的位置,在此之前我們先將imageView.image
設定為PlaceHolder.png
圖片,等待重新布局完後再將原本的圖片設定回去就可以了