Search code examples
iosswiftuitableviewuiscrollviewconstraints

UIScrollView height not updated dynamically based on views size?


I have VC, in that i added UIScrollView -> UIView. After that i added 3 tableViews and i added constraints. Based on content tableViews sized dynamically, for example tbl1, tbl2 and tbl3 has 10, 5 and 7 rows respectively. Based on content i want to update my entire view. Here tableViews height updated successfully but not ScrollView.

My Code is...

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    tbl1.delegate = self
    tbl1.dataSource = self
    tbl2.delegate = self
    tbl2.dataSource = self
    tbl3.delegate = self
    tbl3.dataSource = self
}

override func viewDidLayoutSubviews() {

    DispatchQueue.main.async {
        //Update tbl1 frame
        var frame = self.tbl1.frame
        frame.size.height = self.tbl1.contentSize.height
        self.tbl1.frame = frame
        //Update tbl2 frame
        var frame2 = self.tbl2.frame
        let y = self.tbl1.frame.maxY
        frame2.origin.y = y
        frame2.size.height = self.tbl2.contentSize.height
        self.tbl2.frame = frame2
        //Update tbl3 frame
        var frame3 = self.tbl3.frame
        let y2 = self.tbl2.frame.maxY
        frame3.origin.y = y2
        frame3.size.height = self.tbl3.contentSize.height
        self.tbl3.frame = frame3
    }

}

// MARK: - UITableView Delegates
func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if tableView == tbl1 {
        return 10
    } else if tableView == tbl2 {
        return 5
    } else {
        return 7
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if tableView == tbl1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "TBL ONE"

        return cell
    } else if tableView == tbl2 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "TBL TWO"

        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "TBL THREE"

        return cell
    }

}

Solution

  • just add this line to end of your viewDidLayoutSubviews()

    self.scrollView.contentSize.height = self.tbl1.contentSize.height + self.tbl2.contentSize.height + self.tbl3.contentSize.height