15

我遇到了自动/动态 UITableView 部分标题视图的问题,其中包含一个包装的 UILabel ( numberOfLines = 0 )。高度计算不正确,尤其是在您滚动表格并重用视图时。有时 UILabel 会换行,有时会被截断,有时一个或多个标签不可见,有时标签之间有额外的间距。自定义视图包含一个带有三个 UILabel 的垂直 UIStackView,其中一个会换行。

可以在https://github.com/outerstorm/tableviewHeaderTest找到演示该问题的完整示例应用程序。

部分标题高度在 viewDidLoad 中设置为自动,如下所示:

    tableView.sectionHeaderHeight = UITableViewAutomaticDimension
    tableView.estimatedSectionHeaderHeight = 30.0

并且还实现了以下 heightForHeaderInSection 只是为了让它工作:

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return UITableViewAutomaticDimension
}

我也试过在不同的地方调用setNeedsLayout()layoutIfNeeded()都无济于事。任何建议将不胜感激。

下面是在应用程序中看到的行为的屏幕截图。第一段被截断,第二段太高:

在此处输入图像描述

4

6 回答 6

3

我最近遇到了这种问题。

我通过设置preferredMaxLayoutWidth多行标签来解决它,即

在标签中设置值之前,将它们设置preferredMaxLayoutWidth为:

self.label1.preferredMaxLayoutWidth = self.label1.frame.size.width
self.label2.preferredMaxLayoutWidth = self.label2.frame.size.width
self.label3.preferredMaxLayoutWidth = self.label3.frame.size.width
于 2017-05-29T10:11:06.297 回答
3

只需添加estimatedHeightForHeaderInSection功能并返回您的估计高度。它将解决您的问题。从这里下载修改后的项目

func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat 
{
    return 30;
}
于 2017-05-30T12:47:25.350 回答
1

一种解决方法可以将标题视图保存在数组中,然后从估计的高度方法返回视图的高度

for _ in 0 ..< data.count {

        let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomHeaderView") as! CustomHeaderView
        view.setup()
        headerViews.append(view)
    }


func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat
{
    let view = headerViews[section] as? UIView
    return (view?.frame.size.height)!
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    return headerViews[section] as? UIView
}
于 2017-05-31T09:01:37.540 回答
1

一般来说

heightForHeaderInSection

总是在之前调用

viewForHeaderInSection

使用 UITableViewAutomaticDimension 时,sectionheader 高度只会计算一次,除非手动调用 tableview.reloadData()。

在代码中,您每次都更改节标题文本。高度是第一次计算的,不会自动改变。

您可以将设置功能更改为:

func setup(someNum: Int) {

    let text = String(repeating: "This is where the really long text goes so that it will wrap lines appropriately", count: someNum)

    mainLabel.text = text
}

并将节索引传递给函数

于 2017-05-25T05:52:17.283 回答
1

从代码的文档中:

// tableView:titleForHeaderInSection: or tableView:titleForFooterInSection: if the title is not nil.

换句话说。UITableViewAutomaticDimension仅在您使用titleForHeaderInSection或提供章节标题时使用titleForFooterInSection

于 2018-10-31T22:43:30.350 回答
0

添加

self.label1.preferredMaxLayoutWidth = self.label1.frame.size.width
self.label1.numberoflines = 0;
self.label1.linebreakmode = NSLineBreakByWordWrapping;

awakeFromNib方法中或 请检查一次

于 2017-05-31T10:30:30.040 回答