我有一个以编程方式制作的 tableView。我初始化了部分和行的大小。我还在 Storyboard中放置了一个包含 tableView 的 containerView。我的问题是,我的表格 View 无法正确滚动。
这是我的 Storyboard:
这将是我在 Storyboard中查看 View 的导出:
@IBOutlet weak var trainingDetailsContainerView: UIView!
这是我初始化的表:
var moduleLessonsTableView: UITableView = {
let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
// tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.backgroundColor = Themes.gray_dec
tableView.sectionHeaderHeight = 35
tableView.rowHeight = 50
tableView.isScrollEnabled = true
tableView.register(TrainingModulesTableViewCell.self, forCellReuseIdentifier: "ModuleLessonsCell")
return tableView
}()
这里是我设置 tableView、高度和所有内容的地方:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
moduleLessonsTableView.frame = CGRect(x: 0, y: 0, width: trainingDetailsContainerView.frame.width, height: trainingDetailsContainerView.frame.height)
trainingDetailsContainerView.addSubview(moduleLessonsTableView)
}
我可以尝试将其放入 viewWillAppear 中,高度将正确渲染,这让我意识到 TrainingDetailsContainerView 的边界是在其他 View 之前设置的,我认为。但问题是它会突然弹出。我真的不希望这样,因为从用户的角度来看,这看起来像是滞后。
任何帮助将不胜感激。
我也无法标记 View 生命周期,所以我将其放在这里。
最佳答案
尝试在 viewDidLoad
中向表格 View 添加约束,而不是设置框架。还要从 viewWillAppear
方法中删除代码。
示例代码:
override func viewDidLoad() {
super.viewDidLoad()
trainingDetailsContainerView.addSubview(moduleLessonsTableView)
moduleLessonsTableView.topAnchor.constraint(equalTo: trainingDetailsContainerView.topAnchor).isActive = true
moduleLessonsTableView.leadingAnchor.constraint(equalTo: trainingDetailsContainerView.leadingAnchor).isActive = true
moduleLessonsTableView.trailingAnchor.constraint(equalTo: trainingDetailsContainerView.trailingAnchor).isActive = true
moduleLessonsTableView.bottomAnchor.constraint(equalTo: trainingDetailsContainerView.bottomAnchor).isActive = true
}
关于swift - tableView 在 UIView 内无法正确滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59372513/