Search code examples
swiftviewuiviewtableviewframe

tableView not scrolling properly inside UIView


I have a tableView made programmatic. I initialised the size of the section and the row. I also put a containerView inside the storyboard which would contain the tableView. My problem is, my table view wouldn't scroll properly.

Here would be my storyboard:

enter image description here

Here would be my outlet for the view in the storyboard:

@IBOutlet weak var trainingDetailsContainerView: UIView!

Here would be my initialized table:

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
}()

And here is where I would set up my tableView, heights and all:

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)
}

I can try putting it in viewWillAppear and the height would render correctly, which had me realizing the bounds of the trainingDetailsContainerView is set before the other views, I think. But the problem with it is it will suddenly pop up. I really don't want that as it looks like a lag from a user's perspective.

Any help would be greatly appreciated.

I also can't tag view lifecycles so I'll just put this here.


Solution

  • Try to add constraints to your table view in viewDidLoad instead of setting frame. Also remove code from viewWillAppear method. Example code:

    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
    }