ios - uitableview 之前 View 的动态 UILabel 大小

标签 ios swift dynamic autolayout uilabel

我在尝试让此帖子描述标签根据 IOS9 上的内容大小增大和缩小时遇到了一些麻烦。我有一个 View (我将其称为topView),我将其用作表格 View 的标题(因此,当我向上滚动时,标题消失)。在topView内部,有一堆堆栈 View 。我希望根据内容大小来增大和缩小帖子描述标签的高度。我确实知道如何在简单的情况下执行此操作,其中所有内容都在原型(prototype)单元格内(即设置估计行高并设置 uitableviewautomaticDimensions,在标签上设置 sizetoFit 并将行数更改为 0)。但是,这是一种不同的情况,因为帖子描述标签并不真正位于单元格内部,而是位于 TableView 单元格之前的 View 中。

请注意, View 中的所有项目都具有静态高度,除了 postdescription 标签。帖子描述标签位于仅左右固定的堆栈 View 内(这样顶部和底部会增长?)。此外,包含所有元素的主堆栈 View 固定在四个侧面,包含主堆栈 View 的顶 View 也固定在四个侧面。通过这种设置,我预计顶 View 会根据内容大小而增大和缩小。但是,我在输出中没有看到这一点。我不知道是堆栈 View 持有拒绝增长的标签,还是顶 View 拒绝增长以便为标签的堆栈 View 留出更多空间。谢谢

dynamic uilabel

更新

谢谢 Riadluke,我尝试按照建议做一些事情,即在计算所需高度后调整 headerview 的大小。我已将以下代码放置在 viewDidLayoutSubview 中,它可以解决问题

postDescriptionLbl.sizeToFit()


let headerView = commentTableView.tableHeaderView!

headerView.setNeedsLayout()
headerView.layoutIfNeeded()

let height = TopStackView.frame.size.height + ImageStackView.frame.size.height + postDescriptionLbl.frame.size.height + SpacerStackView.frame.size.height + BottomStackView.frame.size.height
 headerView.frame.size.height = height
commentTableView.tableHeaderView = headerView

我现在使用此方法遇到的问题是,当 View Controller 出现时,我可以实际看到 postDescription 标签高度从 Storyboard中的默认高度增长到所需的高度。例如,当 VC 第一次出现时,我看到一行标签,其中一些字符串被切断,但是 0.5 秒后,标题 View 和标签增长到我想要的大小。我知道这是预期的,因为我在 viewDidLayout subview 之后调用操作。我想知道是否有更好的方法,使我看不到这种过渡,并且 View 立即看起来是正确的高度。 IE。让 View 确切地知道标签有多高,以确定 headerview 在出现在屏幕上之前需要多高?

最佳答案

恐怕设置为 UITableViewtableHeaderView 的 View 不会自动调整大小。它的高度将固定为 IB 中的高度。 您要做的就是手动设置其大小,然后将其重新分配为 tableHeaderView,以便它以您想要的高度显示。

由于您使用的是自动布局,因此可能只需要几行。 您可以在设置标题 View 的内容后立即尝试此代码:

    //for the target size you have set the width as your tableView's width when it is already displayed on screen.
    //note that when it is accesed inside viewDidLoad the tableView's bounds
    //may be different to the actual bounds it will be displayed with,
    //here I am just using the screen bounds
    let targetSize = CGSize(width: UIScreen.mainScreen().bounds.width, height: 10000)

    //set the tableHeader's size to its size after its layout constraints are resolved
    tableHeader.bounds.size =  tableHeader.systemLayoutSizeFittingSize(targetSize)

    //reassign it as the tableHeaderView to update the height it will be displayed in
    tableView.tableHeaderView = tableHeader

关于ios - uitableview 之前 View 的动态 UILabel 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38172150/

相关文章:

python - Python 中的魔法导入

c++ - 迭代器在最后一个元素上返回 "Junk"

ios - 如何过滤 [[String :String]] using UISearchBar and display as String 类型的数组

ios - Xcode 6 Interface Builder View 大小错误

sql - 动态SQL合并纵横表

ios - 将带有源的 Pod 依赖项添加到 .podspec

ios - [NSObject : AnyObject] ?' does not have a member named ' subscript' error in Xcode 6 beta 6

ios - iAd 默认横幅尺寸不正确

ios - 快速框架中的编译器标志

ios - Objective-C:从JSON获取图像