swift - tableView 在 UIView 内无法正确滚动

标签 swift view uiview tableview frame

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

这是我的 Storyboard:

enter image description here

这将是我在 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/

相关文章:

ios - 具有不同类型 JSON 数据的通用 UITableViewCell

ios - Swift 3 UIView 动画

menu - vaadin View 子菜单代码

view - SwiftUI 问题将变量传递给另一个 View

ios - UILabel 在 3.5 英寸 iPhone 4 屏幕上被截断?

ios - UIView 方法 swizzling swift 3

arrays - 如何将两个 Unicode 字符合并为一个

PostgreSQL View 创建巨大的临时文件

ios - 设置 self.view = nil 的效果

iOS - 带有布局指南的 UITabBar 上方的 UIView