iOS 8中的新功能是,您只需设置估计的行高即可获得100%的动态表格视图单元格,然后使用自动布局在单元格中布局您的元素.如果内容高度增加,单元格的高度也会增加.这非常有用,我想知道表视图中的节标题是否也能完成同样的壮举?

例如,可以在tableView:viewForHeaderInSection:中创建UIView,添加UILabel子视图,根据视图指定标签的自动布局约束,并增加视图的高度以适应标签的内容,而不必实现tableView:heightForHeaderInSection:吗?

viewForHeaderInSection的文档声明:"只有在实现tableView:heightForHeaderInSection:时,此方法才能正确工作."我还没有听说iOS8有什么变化.

如果不能做到这一点,那么模仿这种行为的最佳方式是什么呢?

推荐答案

这是可能的.它与iOS 8中引入的动态单元高度并驾齐驱.

要执行此操作,请使用自动标注横断面页眉高度,如果需要,可以提供估计的横断面页眉高度.这可以在 Select 表视图时在界面生成器中完成,也可以以编程方式完成:

Table view configuration in storyboard

tableView.sectionHeaderHeight = UITableView.automaticDimension
tableView.estimatedSectionHeaderHeight = 38

//You can use tableView(_:heightForHeaderInSection:) and tableView(_:estimatedHeightForHeaderInSection:)
//if you need to support different types of headers per section

然后实现tableView(_:viewForHeaderInSection:),并根据需要使用自动布局来约束视图.确保完全约束到UITableViewHeaderFooterViewcontentView,特别是从上到下,以便高度可以由约束确定.就这样!

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {    
    let headerView = UITableViewHeaderFooterView()
    headerView.translatesAutoresizingMaskIntoConstraints = false
    headerView.backgroundView = {
        let view = UIView()
        view.backgroundColor = myCustomColor
        return view
    }()

    let headerLabel = UILabel()
    headerLabel.translatesAutoresizingMaskIntoConstraints = false
    headerLabel.text = "Hello World"
    headerView.contentView.addSubview(headerLabel)
    
    NSLayoutConstraint.activate([
        headerLabel.leadingAnchor.constraint(equalTo: headerView.contentView.leadingAnchor, constant: 16),
        headerLabel.trailingAnchor.constraint(equalTo: headerView.contentView.trailingAnchor, constant: -16),
        headerLabel.topAnchor.constraint(equalTo: headerView.contentView.topAnchor, constant: 12),
        headerLabel.bottomAnchor.constraint(equalTo: headerView.contentView.bottomAnchor, constant: -12)
    ])
    
    return headerView
}

Ios相关问答推荐

如何从ipad获取用户定义的设备名称,IOS版本应大于16在flutter

使用CGAffineTransform旋转视图只起作用一次吗?

Flutter 应用程序中带有Firebase的GoogleService-Info.plist中缺少CLIENT_ID、REVERSED_CLIENT_ID和ANDROID_CLIENT-ID

如何在 Flutter 应用程序中测试来自 App/Play Store 的移动深层链接?

在 SwiftUI 中以编程方式插入内嵌图像

iOS设备网页自动化中,在向字段发送文本后未启用按钮

实现 ListView Builder Widget Flutter 后退按钮不起作用

SwiftUI - TextField - 在焦点上清除 Double 类型的值,在取消 Select 时恢复

使用 SwiftUI 显示多个 VNRecognizedObjectObservation 边界框时偏移量错误

为什么 Swift 不在启动的同一线程上恢复异步函数?

如何在 SwiftUI 中创建两个大小相同的正方形占据整个屏幕宽度?

在 SwiftUI 中使用 .rotation3DEffect 在视图之间翻转

使用 SceneKit 从 CapturedRoom.walls 重新创建 RoomPlan

帧过渡动画有条件地工作

我可以在 Apple-Watch 上使用 iPhone 的摄像头扫描 SwiftUi 中的二维码(例如用于登录)吗

如何将标准化坐标系中的点的位置转换为具有相对位置的常规坐标系?

何时需要将应用程序源包含在测试目标中?

是否可以将 Socket.io 与 AWS Lambda 一起使用?

Parse for iOS:try 运行应用程序时出错

我的应用程序因使用广告支持框架而被拒绝.哪个图书馆负责?