首页 > 解决方案 > UITableView 动态高度不改变 iOS

问题描述

拖放 UITableViewHeader

在此处输入图像描述

你可以看一个橙色的 UITextView。

在此处输入图像描述

我将tableview的高度常数设置为零。

重新加载 UITableView 的 tableview 总高度后显示与以前相同(因为没有 UITextView 显示)

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.heightConstCommentBox.constant = 0;

    [self configureTableviewFooter];

}

-(void)configureTableviewFooter{
    //More button Configure

    height =  50 +[self recusiveDescription:self.viewFooter] ;

    // Assign new frame
    self.viewFooter.frame =  CGRectMake(self.viewFooter.frame.origin.x, 
    self.viewFooter.frame.origin.y,self.viewFooter.frame.size.width ,  height); // viewFooter is container view of tableFooterView

    self.tableView.tableFooterView = self.viewFooter;
    [self.tableView reloadData];

}

- (float )recusiveDescription:(UIView *)view
{
    NSString *s = @"";
    float height = 0;

    NSArray *subviews = [view subviews];
    if ([subviews count] == 0) return 0;

    for (UIView *subView in subviews) {

    height = height + subView.frame.size.height ;

        [self recusiveDescription:subView];
    }
    return height;
}

重新加载 tableview 后,表格视图页脚大小不会改变。

标签: iosobjective-cuitableview

解决方案


如果您使用自定义单元格作为表格,您可以使用以下内容。

在以下代码中,将posts[index.row].post替换为您的标签内容,+230 是您单元格的最小高度。或者你可以说它在标签以外的其他视图的高度。

仅当您有 1 个标签或 1 个文本字段、1 个文本视图时,自动尺寸方法才有效。

并且不要固定标签的高度。

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let heightOfRow = self.calculateHeight(inString: postss[indexPath.row].post)
    return (heightOfRow + 230)
}

//custom function for calculate dynamic height
func calculateHeight(inString:String) -> CGFloat
{
    let messageString = inString
    let attributes : [NSAttributedString.Key : Any] = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15.0)]

    let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)

    let rect : CGRect = attributedString.boundingRect(with: CGSize(width: 370, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil)

    let requredSize:CGRect = rect
    return requredSize.height
}

推荐阅读