Ios 使用textView自定义单元格大小
我有一个带有自定义单元格的tableView(带有textView的单元格),我想根据文本大小调整其中一些单元格的大小。我使用以下代码段执行此操作:Ios 使用textView自定义单元格大小,ios,iphone,objective-c,uitableview,Ios,Iphone,Objective C,Uitableview,我有一个带有自定义单元格的tableView(带有textView的单元格),我想根据文本大小调整其中一些单元格的大小。我使用以下代码段执行此操作: - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ //Load text in NSString which you want in Cell's LabelText. NSString *
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//Load text in NSString which you want in Cell's LabelText.
NSString *cellText;
cell.Text = someData
//define font for Labeltext...
UIFont *cellFont = [UIFont fontWithName:@"Georgia" size:19.0];
CGSize constraintSize = CGSizeMake(330.0f, MAXFLOAT);
CGSize labelSize_val = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
return labelSize_val.height + 20;
}
此代码在某些情况下正常工作(红色正方形-单元格空间):
但是,对于较大的文本,它不能正常工作(使单元格变大,并留有空白):
有什么办法解决这个问题吗?我已经用过了,对我来说效果很好
if (SYSTEM_VERSION_LESS_THAN(@"7.0")) {
// code here for iOS 5.0,6.0 and so on
CGSize fontSize = [text sizeWithFont:[UIFont fontWithName:@"Helvetica" size:17]];
size = fontSize;
}
else {
// code here for iOS 7.0
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:@"Helvetica" size:17], NSFontAttributeName,
nil];
CGRect fontSizeFor7 = [text boundingRectWithSize:CGSizeMake(571, 500)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributesDictionary
context:nil];
size = fontSizeFor7.size;
}
return size.height +20 ;
首先,您必须重写Indexpath处的行高度,并通过函数计算字符串的高度“
我希望这段代码对你有帮助。这是
[UIFont fontWithName:@“Georgia”大小:19.0];
正是你用来显示的字体吗?如果这比实际字体小,它将计算更大的高度是的,这正是我用来在单元格中显示文本的字体
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *cellText;
cellTextHeight = [self heightOfCellForText:cellText];
return cellTextHeight+margin;
}
-(CGFloat)heightOfCellForText:(NSString *)yourString
{
CGRect r = [yourString boundingRectWithSize:CGSizeMake(100.0, 0)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:[UIFont fontWithName:@"Arial" size:15]} context:nil];
CGSize size=r.size;
CGFloat height=size.height;
return height;
}