在作tableView的時候,咱們有時候須要根據cell的高度動態來調整,最近在網上看到一段代碼不錯,跟你們Share一下。xcode
在字體
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ui
類中獲取cell的高度:
- CGSize boundSize = CGSizeMake(216, CGFLOAT_MAX);
- cell.textLabel.text = @"12345678900123456789";
- cell.userInteractionEnabled = NO;
- cell.textLabel.numberOfLines = 0;
- CGSize requiredSize = [cell.textLabel.text sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:boundSize lineBreakMode:UILineBreakModeWordWrap];
- CGRect rect = cell.frame;
- rect.size.height = requiredSize.height+5;
- cell.frame = rect;
這時候獲取到了cell的高度,而後在
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {spa
類中改變cell的高度:
- UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
-
- NSLog(@"cell height %f",cell.frame.size.height);
-
- return cell.frame.size.height;
這樣以來cell的高度就根據cell裏label的內容自動改變啦。
其主要出發點就是我有一個label,而後我要把這個label展現出來,我根據字體的大小還有行數來獲取一個高度,這樣cell的高度就有啦.net