表格视图未反映尺寸变化的问题通常是由于表格视图的布局或约束没有正确设置导致的。下面是一个示例解决方法,可以用来解决这个问题:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// 创建表格视图
tableView = UITableView(frame: view.bounds, style: .plain)
tableView.delegate = self
tableView.dataSource = self
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // 设置自动调整大小的mask
view.addSubview(tableView)
// 注册单元格
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
// MARK: - UITableViewDataSource methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "Row \(indexPath.row)"
return cell
}
// MARK: - UITableViewDelegate methods
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
// MARK: - UIViewController methods
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// 更新表格视图的frame
tableView.frame = view.bounds
}
}
在上面的代码中,我们创建了一个表格视图并将其添加到视图控制器的视图中。我们还设置了表格视图的autoresizingMask
属性,以便当父视图的大小发生变化时,表格视图可以自动调整大小。
在viewDidLayoutSubviews
方法中,我们更新了表格视图的frame,以确保其始终与父视图的尺寸保持一致。
这样,无论父视图的尺寸如何改变,表格视图都会正确地调整大小并反映尺寸变化。
上一篇:表格视图随导航栏标题滚动