[英]How to get height of dynamically created UITextView iphone
我正在尝试创建一个表格,其中包含包含 UITextViews 的单元格,用于可变数量的文本。 我需要指定每个单元格的高度以匹配文本视图的内容大小。 我在用...
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
UITextView *historyNode = [[[UITextView alloc]init]autorelease];
historyNode.text = (@"%@",[globalArrayWithStrings objectAtIndex:[indexPath row]]);
NSLog(@"%2.0f",historyNode.frame.size.height);
return historyNode.contentSize.height;
}
由于某种原因,它总是打印 0。如果我打印在界面生成器中创建的 textview 的高度,它会打印正确的值。 任何想法如何解决这个问题,或者为什么我无法获得 textview 的大小,直到它被添加到视图中。
您可以使用sizeWithFont:方法来查找动态高度。 你的heightForRowAtIndexPath:应该是这样的。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *text = [globalArrayWithStrings objectAtIndex:[indexPath row]];
CGSize maxSize = CGSizeMake(textViewWidth, 999); // 999 can be any maxmimum height you want
CGSize newSize = [text sizeWithFont:aFont constrainedToSize:maxSize lineBreakMode:textViewLineBreakMode];
return newSize.height;
}
首先设置 uitextView 的框架,然后您将获得文本视图的高度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.