tableview和cell高度自適應
阿新 • • 發佈:2019-01-07
普通(簡化)版【推薦使用】:tableview 高度自適應設定只需要2步
1. >> 設定cell高度自適應: // cell佈局設定好之後呼叫此方法就可以實現高度自適應(注意:如果用高度自適應則不要再以cell的底邊為參照去佈局其子view) [cell setupAutoHeightWithBottomView:_view4 bottomMargin:10]; 2. >> 獲取自動計算出的cell高度 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { id model = self.modelsArray[indexPath.row]; // 獲取cell高度 return [self.tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[DemoVC9Cell class] contentViewWidth:cellContentViewWith];
}
升級版(適應於cell條數少於100的tableview):tableview 高度自適應設定只需要2步
1. >> 設定cell高度自適應: // cell佈局設定好之後呼叫此方法就可以實現高度自適應(注意:如果用高度自適應則不要再以cell的底邊為參照去佈局其子view) [cell setupAutoHeightWithBottomView:_view4 bottomMargin:10]; 2. >> 獲取自動計算出的cell高度 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { // 獲取cell高度 return [self cellHeightForIndexPath:indexPath cellContentViewWidth:[UIScreen mainScreen].bounds.size.width]; }
普通view的自動佈局:
用法示例
/* 用法一 */ _view.sd_layout .leftSpaceToView(self.view, 10) .topSpaceToView(self.view, 80) .heightIs(130) .widthRatioToView(self.view, 0.4); /* 用法二 (一行程式碼搞定,其實用法一也是一行程式碼) */ _view.sd_layout.leftSpaceToView(self.view, 10).topSpaceToView(self.view,80).heightIs(130).widthRatioToView(self.view, 0.4); >> UILabel文字自適應: // autoHeightRatio() 傳0則根據文字自動計算高度(傳大於0的值則根據此數值設定高度和寬度的比值) _label.sd_layout.autoHeightRatio(0); ******************************************************************************* 注意:先把需要自動佈局的view加入父view然後在進行自動佈局,例: UIView *view0 = [UIView new]; UIView *view1 = [UIView new]; [self.view addSubview:view0]; [self.view addSubview:view1]; view0.sd_layout .leftSpaceToView(self.view, 10) .topSpaceToView(self.view, 80) .heightIs(100) .widthRatioToView(self.view, 0.4); view1.sd_layout .leftSpaceToView(view0, 10) .topEqualToView(view0) .heightRatioToView(view0, 1) .rightSpaceToView(self.view, 10); *******************************************************************************
自動佈局用法簡析
1.1 > leftSpaceToView(self.view, 10)
方法名中帶有“SpaceToView”的方法表示到某個參照view的間距,需要傳遞2個引數:(UIView)參照view 和 (CGFloat)間距數值
1.2 > widthRatioToView(self.view, 1)
方法名中帶有“RatioToView”的方法表示view的寬度或者高度等屬性相對於參照view的對應屬性值的比例,需要傳遞2個引數:(UIView)參照view 和 (CGFloat)倍數
1.3 > topEqualToView(view)
方法名中帶有“EqualToView”的方法表示view的某一屬性等於參照view的對應的屬性值,需要傳遞1個引數:(UIView)參照view
1.4 > widthIs(100)
方法名中帶有“Is”的方法表示view的某一屬性值等於引數數值,需要傳遞1個引數:(CGFloat)數值