我在TableView Cell中使用UITextView。为此,我必须计算UITextview的高度。
经过大量的磨头后,我找到了一种合理可靠的方法来计算UITextView的高度。我复制了与Cell相同的虚拟UITxtView并分配了文本。在设置框架后,我从textView.frame.size.height获取高度。
但是只有在为textView分配长的unicode文本时才会出现问题。
这是func
-(float)calculateHeight:(NSString*)msg nick:(NSString*)nick
{
textView = [[UITextView alloc] init];
PrivateChatCellRight * pc = [[PrivateChatCellRight alloc] init];
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"PrivateChatCellRight" owner:nil options:nil];
for(id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[PrivateChatCellRight class]])
{
pc = (PrivateChatCellRight *)currentObject;
break;
}
}
textView = pc.lblMessage;
{
textView.text = msg;
if ([textView respondsToSelector:@selector(setAttributedText:)])
{
UIFont *boldFont = MyriadProBoldWithSize13Pt;
UIFont *regularFont = btMyriadProRegularWithSize14Pt; //font from define
// Creating simmilar attributes
NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:
regularFont, NSFontAttributeName,
nil];
NSDictionary *subAttrs = [NSDictionary dictionaryWithObjectsAndKeys:
boldFont, NSFontAttributeName, nil];
const NSRange range = NSMakeRange(0,2); // range of " 2012/10/14 ". Ideally this should not be hardcoded
// Create the attributed string (text + attributes)
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@: %@", nick ,msg]
attributes:attrs];
[attributedText setAttributes:subAttrs range:range];
// Set it in our UILabel and we are done!
[textView setAttributedText:attributedText];
}
else
{
}
textView.textColor = textSettingsColor;
[textView sizeToFit];
NSLog(@"height %f", textView.frame.size.height);
textView.frame = CGRectMake(textView.frame.origin.x, textView.frame.origin.y, textView.frame.size.width + 5, textView.frame.size.height + 5);
return textView.frame.size.height;
}
}