iOS 8 Tableview根據AutoLayout自動調整高度,iostableview高度

來源:互聯網
上載者:User

iOS 8 Tableview根據AutoLayout自動調整高度,iostableview高度

原創Blog,轉載請註明出處
blog.csdn.net/hello_hwc

前言:在iOS 8之前,如果要讓Tableview根據內容自動調整大小的話,需要動態去計算每個cell的高度。太尼瑪操蛋了。iOS 8之後,可以根據AutoLayout來自動調整高度了,原理很簡單。

  • DataSource中選擇讓iOS自動計算
  • 在Cell中,設定能夠讓iOS計算出高度的AutoLayout,注意,這裡一定要是能夠計算出高度的AutoLayout,這和傳統的不一樣。
效果

完整過程

建立一個基於singleview的工程,然後刪除預設Storyboard的ViewController,拖拽一個TableviewController,設定為inital Controller

往Prototype Cells上拖拽兩個UILabel


設定cell 的reuse identifier為cell

為兩個Label設定屬性
Title
設定tag為10

Detail
設定tag為11

為兩個Label設定AutoLayout
Title

Detail

注意,這裡把title放在左上方,Detail放在左下角。然後添加二者之間的距離恒定為1,那麼AutoLayout就會自動計算出高度。

建立一個TableviewController,並且講storyboard上的tableviewController設定為建立的類

設定Tableview的高度為自動擷取

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{    return UITableViewAutomaticDimension;}-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    return UITableViewAutomaticDimension;}

加入儲存資料的數組,並且在初始化裡設定資料

@property (strong,nonatomic)NSArray * titleArray;@property (strong,nonatomic)NSArray * detailArray;
- (void)viewDidLoad {    [super viewDidLoad];    self.titleArray = @[@"1",@"2",@"3"];    self.detailArray = @[@"shot",@"Aduahguhauhguhaudghuahguhudhauhg",@"dhuahgudhaughuahdughuahguhauhguhdahudhuahughduahguhadguhaduhguadhughduahguahguhadugh"];}

接下來就是Tablview的常用的,很好理解,這裡不多贅述

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {    return 1;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {    return self.titleArray.count;}-(BOOL)prefersStatusBarHidden{    return true;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];    UILabel * titleLabel = (UILabel *)[cell viewWithTag:10];    UILabel * contentLabel = (UILabel *)[cell viewWithTag:11];    titleLabel.text = self.titleArray[indexPath.row];    contentLabel.text = self.detailArray[indexPath.row];    contentLabel.numberOfLines = 0;    return cell;}

然後,就得到了我們想要的效果了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.