如何讓 UITableViewCell 中的 imageView 大小固定,cell.imageview大小

來源:互聯網
上載者:User

如何讓 UITableViewCell 中的 imageView 大小固定,cell.imageview大小

UITableView可以算是使用頻率最高的組件之一的,在開發過程中經常需要展示一些簡單的資訊列表
常見列表布局

,很多頁面其實就是這種展示結果,通常需要imageView,textLabel,detailTextlabel,而UITableViewCell本身提供了方便的自動布局(當有圖片和沒圖片時,textLabel和detailLabel的位置會左右自動調整). 但是圖片的大小卻是沒有辦法固定的(直接設定imageView.frame是無法固定imageView的大小的),那麼一般來說解決這個問題的辦法有兩種:

  • 固定顯示圖片的大小(包括PlaceHolder)
  • 自訂tableViewCell,添加自訂的imageView,textLabeldetailTextLabel

這兩種方式都可以解決這個問題,但是這兩種方式其實都挺麻煩的,能否直接固定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來顯示預設圖片).

原理是在UItableVeiwlayoutSubviews調用時,會根據imageView.image的大小來調整imageView,textLabel,detailTextLabel的位置,在此之前我們先將imageView.image設定為PlaceHolder.png圖片,等待重新布局完後再將原本的圖片設定回去就可以了

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.