『導(dǎo)言』
iOS開發(fā)中殴胧,對于一個列表中的UITableViewCell行的字符串高度不一致,那么怎樣才能全部顯示字符串戳鹅?(高度自適應(yīng)demo下載)
-
方法:
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSString *, id> *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);
- 需要傳入
字符串
str,寬度
w, 最大高度
MAXFLOAT ,字體
font大小均驶,得到rect
高度自適應(yīng).gif -
代碼:
#pragma mark- UITableViewDatasourece
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.tableSource.count;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* identifier = @"customCell";
static BOOL isRegister = NO;
if (!isRegister) {
UINib* cellNib = [UINib nibWithNibName:@"GCZCell" bundle:nil];
[tableView registerNib:cellNib forCellReuseIdentifier:identifier];
isRegister = YES;
}
GCZCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
// 表格內(nèi)容的設(shè)置
GCZModel* model = self.tableSource[indexPath.row];
cell.iconView.image = [UIImage imageNamed:@"36_8.jpg"];
cell.titleLabel.text = model.likeCount;
// 先計算出要加載的字符串按照177寬,字體大小為17排版需要的rect
// w == 177 ; h = 998\MAXFLOAT(無限大)
CGRect rect = [model.comment boundingRectWithSize:CGSizeMake(177, 998) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:17]} context:nil];
CGRect labelFrame = cell.contenLabel.frame;
//w == 177 h=?
NSInteger h = rect.size.height+10;
NSLog(@"\nh = %d\n-----------------------",h );
// 根據(jù)要顯示內(nèi)容排版的高度枫虏,重新設(shè)置label的高度
CGRect newFrame = CGRectMake(labelFrame.origin.x, labelFrame.origin.y, 177, rect.size.height+10);
[cell.contenLabel setFrame:newFrame];
[cell.contenLabel setLineBreakMode:NSLineBreakByCharWrapping];
cell.contenLabel.numberOfLines = 0;
// 設(shè)置label的內(nèi)容
cell.contenLabel.text = model.comment;
return cell;
}