Last active
June 30, 2024 00:06
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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