我有UITableView,每个tableViewCell都是自定义的。在我的customTableViewCell内部是一个UITextView,TextViews框架的引脚或与其superView相同,即tableViewCell。
我将如何动态设置UITableViewCell高度,该高度与TextViews大小成正比,后者也取决于我从互联网上获得的内容文本。
(样本原型)
//这就是我操纵每个单元格高度的方式
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
// How do I set the height here, whats the best approach for this. with autolayout BTW
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// I initialize every cell here with my ArrayContainer, nothing much to refer here.
}
答案 0 :(得分:7)
请按照以下回答:Link reference
为您的UITextView添加一个高度约束,并为您的自定义单元格类创建一个插座。
在sizeThatFits:
上使用UITextView
获取适合内容的大小,并将此值设置为2中所述约束的constant
。在{{1}中执行此操作}}
有一点需要注意的是,如果有很多单元格(数百或数千),那么您可能会遇到性能问题。
答案 1 :(得分:1)
主要获取texts as NSArray
并将其作为临时分配到UITextView中,这样您就可以获得单元格高度:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGRect frame;
// set the height here, According to the NSArray of text
if(textView || section )
UITextView *tempTxtView = [[UITextView alloc] init];
tempTxtView.text = // Add the Text of index according to the Section
// Fit the UITextView to the Content
frame = tempTxtView.frame;
frame.size.height = tempTxtView.contentSize.height;
tempTxtView.frame = frame;
}
return frame.size.height;
}
获得UITableViewCell高度:然后无需担心这个,对吧?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// I initialize every cell here with my ArrayContainer, nothing much to refer here.
self.textView = [[UItextView alloc] initWithFrame:CGRectMake(cell.frame.origin.x +20, cell.frame.origin.y +10, cell.frame.size.width - 20, cell.frame.size.height - 20)];
// ....... Do further with the NSArray of Text
}
注意:我没有经过测试,只是一个想法。希望这会对你有所帮助
答案 2 :(得分:0)
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGSize titlesize = [TxtValue.text sizeWithFont:[UIFont fontWithName:appdel.strFont size:25.0f] constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping]; /// ----- -set width as per your requirement inplace of 300
return titlesize.height+10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
}