首页 > 解决方案 > tableView 在 UIView 内无法正确滚动

问题描述

我有一个以编程方式制作的 tableView。我初始化了部分和行的大小。我还在情节提要中放置了一个 containerView,其中包含 tableView。我的问题是,我的表格视图无法正确滚动。

这将是我的故事板:

在此处输入图像描述

这将是我在情节提要中查看视图的出路:

@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 的边界设置在其他视图之前,我想。但它的问题是它会突然弹出。我真的不希望这样,因为从用户的角度来看,它看起来像是一个滞后。

任何帮助将不胜感激。

我也不能标记视图生命周期,所以我就把它放在这里。

标签: swiftviewuiviewtableviewframe

解决方案


尝试在表格视图中添加约束viewDidLoad而不是设置框架。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
}

推荐阅读