Skip to content

Instantly share code, notes, and snippets.

@crisbit
Last active July 7, 2023 13:08
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save crisbit/25bc28cee9c1b25fdf0d7e3efa0ff7f4 to your computer and use it in GitHub Desktop.
Save crisbit/25bc28cee9c1b25fdf0d7e3efa0ff7f4 to your computer and use it in GitHub Desktop.
How to make a dynamic height scroll view programmatically in swift (using SnapKit)
import Foundation
class ViewWithDynamicWidthScrollingView: UIView {
convenience init() {
self.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setupHierarchy()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupHierarchy()
}
private func setupHierarchy() {
let scrollView = UIScrollView()
scrollView.backgroundColor = UIColor.whiteColor()
addSubview(scrollView)
scrollView.snp_makeConstraints { make in
make.edges.equalTo(self)
}
let contentView = UIView()
scrollView.addSubview(contentView)
// This is the important part
contentView.snp_makeConstraints { make in
make.edges.equalTo(scrollView)
make.width.equalTo(self)
}
// Make sure each view contained by the content view
// has an height (intrisic or specified)
let blackView = UIView()
blackView.backgroundColor = UIColor.blackColor()
contentView.addSubview(blackView)
blackView.snp_makeConstraints { make in
// The first child view must be pinned to the top
// of the content view
make.top.width.equalTo(contentView)
make.height.equalTo(1000)
}
let redView = UIView()
redView.backgroundColor = UIColor.redColor()
contentView.addSubview(redView)
redView.snp_makeConstraints { make in
make.top.equalTo(blackView.snp_bottom)
make.width.equalTo(contentView)
make.height.equalTo(1000)
// The last child view must be pinned to the bottom
// of the content view
make.bottom.equalTo(contentView.snp_bottom)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment