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;}
然後,就得到了我們想要的效果了。