gpt4 book ai didi

ios - 如何调整 UITableViewCell 的大小以适应其内容?

转载 作者:IT王子 更新时间:2023-10-29 08:04:25 27 4
gpt4 key购买 nike

我有一个包含多个可重用 TableViewCell 的 UITableview。在一个单元格中,我有一个 UITextView,它会自行调整大小以适应其内容。现在我“只需”调整 TableViewCell 的 contentView 大小,这样我就可以阅读 while 文本了。我已经试过了:

cell2.contentView.bounds.size.height = cell2.discriptionTextView.bounds.size.height; 

或者:

cell2.contentView.frame = CGRectMake(0, cell2.discriptionTextView.bounds.origin.y,     
cell2.discriptionTextView.bounds.size.width,
cell2.discriptionTextView.bounds.size.height);

在方法中:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath 
*)indexPath {}

但它不会起作用。

有人知道怎么做吗?

新代码:

    @implementation AppDetail

CGFloat height;


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{…

cell2.TextView.text = self.text;
[cell2.TextView sizeToFit];
height = CGRectGetHeight(cell2.TextView.bounds);

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

if (indexPath.row == 0) {
return 143;
}
if (indexPath.row == 1) {
return height;
}

return 0;
}

最佳答案

您只能在 tableView:heightForRowAtIndexPath: 委托(delegate)方法中调整 UITableViewCell 的大小。

当加载 tableView 时为每一行调用该方法时,您必须估计文本的大小。

这就是我为解决问题所做的。

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString * yourText = self.myArrayWithTextInIt[indexPath.row]; // or however you are getting the text
return additionalSpaceNeeded + [self heightForText:yourText];
}

-(CGFloat)heightForText:(NSString *)text
{
NSInteger MAX_HEIGHT = 2000;
UITextView * textView = [[UITextView alloc] initWithFrame: CGRectMake(0, 0, WIDTH_OF_TEXTVIEW, MAX_HEIGHT)];
textView.text = text;
textView.font = // your font
[textView sizeToFit];
return textView.frame.size.height;
}

编辑

虽然我使用这个解决方案有一段时间了,但我发现了一个我推荐使用的更优化的解决方案,因为它不需要分配整个 textView 即可工作,并且可以处理大于 2000 的文本。

-(CGFloat)heightForTextViewRectWithWidth:(CGFloat)width andText:(NSString *)text
{
UIFont * font = [UIFont systemFontOfSize:12.0f];

// this returns us the size of the text for a rect but assumes 0, 0 origin
CGSize size = [text sizeWithAttributes:@{NSFontAttributeName: font}];

// so we calculate the area
CGFloat area = size.height * size.width;

CGFloat buffer = whateverExtraBufferYouNeed.0f;

// and then return the new height which is the area divided by the width
// Basically area = h * w
// area / width = h
// for w we use the width of the actual text view
return floor(area/width) + buffer;
}

关于ios - 如何调整 UITableViewCell 的大小以适应其内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19211083/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com