公司最近要用到autoLayout,今天看了一些autoLayout相關的東西。臨下班的時候,一個同事問到如何使用autoLayout實現動態計算UITableViewCell高度,因而一塊兒研究了一番,參考了一篇動態計算UITableViewCell高度詳解文章,回家簡單實現了使用autoLayout實現了動態計算UITableViewCell高度。code
實現上面的步驟其實很簡單:input
1.在Cell對應的xib文件中創建完整的約束。it
2.使用[cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]
方法對cell進行動態計算高度,
而後在方法- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
返回cell的高度。io
注意:[cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]
必定是cell.contentView,不能用cell。table
相關代碼:ast
- (void)viewDidLoad{ [super viewDidLoad]; _data = @[@"數據1", @"數據2",@"數據3", @"數據4", @"數據5", @"數據6"]; _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain]; _tableView.delegate = self; _tableView.dataSource = self; [self.view addSubview:_tableView]; _cell = [[[NSBundle mainBundle] loadNibNamed:@"LWCell" owner:self options:nil] lastObject]; _textViewCell = [[[NSBundle mainBundle] loadNibNamed:@"LWTextViewCell" owner:self options:nil] lastObject]; _textViewCell.textView.delegate = self; }
#pragma mark UITableView delegate - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return _data.count+5; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { if(indexPath.row < _data.count){ LWCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PrCell"]; if(cell == Nil){ cell = [[[NSBundle mainBundle] loadNibNamed:@"LWCell" owner:self options:nil] lastObject]; } cell.content = _data[indexPath.row]; return cell; } else { LWTextViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YHTextViewCell"]; if(cell == nil){ cell = [[[NSBundle mainBundle] loadNibNamed:@"LWTextViewCell" owner:self options:nil] lastObject]; cell.textView.delegate = self; } return cell; } }
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { if(indexPath.row < _data.count){ _cell.content = _data[indexPath.row]; CGSize size = [_cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; return size.height+1.0f; } else { CGSize size = [_textViewCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; _textViewCell.textView.text = _inputText; CGSize textViewSize = [_textViewCell.textView sizeThatFits:CGSizeMake(_textViewCell.textView.frame.size.width, 100000.0f)]; return 50 > (size.height + 1.0f + textViewSize.height) ? 50 : (size.height + 1.0f + textViewSize.height); } }
#pragma mark UITextView delegate- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { if ([text isEqualToString:@"/n"]) { NSLog(@"h=%f", textView.contentSize.height); } return YES; }
- (void)textViewDidChange:(UITextView *)textView { _inputText = textView.text; [_tableView beginUpdates]; [_tableView endUpdates]; }