How to Dynamically increase height of Two Tableview in a Scrollview

Viewed 96

I have an issue at the moment I am trying to put two table views inside a scrollview in one controller and these tableview are placed one below another. these two tableview uses scrollview for scrolling. so I used vertical stackview inside scrollview. but when I create cell, both tableview height is not increases as well as scrollview is not able to scroll. How should i use scrollview scroll for scrolling tableview?

-- scrollview -----VerticalStackView --------Tableview 1 --------Tableview 2

I'm really lost with this.Any help will be greatly appreciate it.

1 Answers

You need to make each UITableView define it's own size based on their content. To do that subclass both of them using the class below.

final class ContentSizedTableView: UITableView {
    
    override var contentSize:CGSize {
        didSet {
            invalidateIntrinsicContentSize()
        }
    }

    override var intrinsicContentSize: CGSize {
        layoutIfNeeded()
        return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
    }
}

Then, for each UITableView you need to set isScrollEnabled = false. Otherwise their defined size will be 0.

Then just add each table view to the stack view you're using inside the scrollview. If their combined height is larger than the screen height, it'll scroll.

Related