UITableView动态高度不会更改iOS

时间:2019-07-08 03:04:36

标签: ios objective-c uitableview

拖放UITableViewHeader

enter image description here

您可以查看橙色的UITextView。

enter image description here

我将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后,table view页脚大小不变。

2 个答案:

答案 0 :(得分:0)

在方法recusiveDescription:(UIView *)view中,您使用子视图的frame属性。但是对于自动布局,这是不正确的。要获取future size of the view,请致电:

- (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize 
        withHorizontalFittingPriority:(UILayoutPriority)horizontalFittingPriority 
              verticalFittingPriority:(UILayoutPriority)verticalFittingPriority;

此方法根据提供的约束优先级返回视图的最佳大小。

我也不明白为什么您在recusiveDescription中调用recusiveDescription:并且不使用结果值。

答案 1 :(得分:0)

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

在以下代码中,将 postss [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
}