我试图通过代码设置表视图中节的页脚和页眉的高度,但不起作用.当我在故事板上做的时候,它工作得很好.

这是我的代码

import UIKit

class MyTableViewController: UIViewController {

    @IBOutlet weak var myTable : UITableView!
    
    let spacing : CGFloat = 20
    
    override func viewDidLoad() {
        super.viewDidLoad()
        myTable.delegate = self
        myTable.dataSource = self
    }
}

extension MyTableViewController : UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = myTable.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = "Random text"
        cell.accessoryType = .detailButton
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 5
    }

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

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

代码的输出:

Output of the code

我想在牢房里放些垫子.

推荐答案

默认情况下,如果您不符合,UITableViewDelegate将在viewForHeaderInSection中返回nil(与页脚相同).在故事板中,您可以直接拖动单元格或视图,它代表动态原型,这就是为什么它会一直工作,直到您添加表的Delegate/DataSource.

添加此委托方法:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView()
    view.backgroundColor = .red
    //... some configurations here if needed
    return view
}

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let view = UIView()
    view.backgroundColor = .orange
    //... some configurations here if needed
    return view
}

enter image description here

Swift相关问答推荐

@ MainActor + Combine不一致的编译器错误

阴影动画的动画不流畅

避免嵌套导航TabView

Swift:iVar + Equatable上的协议约束

是否在核心数据中使用Uint?

查找数组中 ** 元素 ** 的属性的最小值和最大值

在Swift中如何将NSUrl转换为本地路径URL

Swift String.firstIndex(of: "\n") 返回 nil,即使字符串有 \n

如何在 SwiftUI 中为过渡动画保持相同的标识

我怎样才能缩短(提高效率)这段代码?

Pod lib lint 命令找不到 watchos 模拟器

展开 List 中的 HStack 以端到端但不是从上到下,因此看起来项目之间有更宽的空间

如何使被拖动的对象成为前景(foreground)对象

找不到接受提供的参数的/的重载

在 iOS 中使用 Swift 保存 PDF 文件并显示它们

Swift 自定义字体 Xcode

调整文本的字体大小以适应 UIButton

如何在 Swift 中将 UILabel 居中?

如何使用 swift 在 tableview 中填充两个不同数组的两个部分?

swift - 我可以从我的自定义初始化方法中调用 struct 默认成员初始化吗?