Created
August 14, 2018 20:31
-
-
Save AAlfare/561189de79265d09fea7a94fa27ae008 to your computer and use it in GitHub Desktop.
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
// | |
// ScrollingStackView.swift | |
// ScrollingStackView | |
// | |
// Created by Andreas Alfarè on 14.08.18. | |
// Copyright © 2018 Andreas Alfarè. All rights reserved. | |
// | |
import UIKit | |
class ScrollingStackView: UIScrollView { | |
var axis: UILayoutConstraintAxis { | |
get { | |
return contentView.axis | |
} | |
set { | |
contentView.axis = newValue | |
setNeedsUpdateConstraints() | |
} | |
} | |
lazy var contentView: UIStackView = { | |
let contentView = UIStackView() | |
contentView.translatesAutoresizingMaskIntoConstraints = false | |
return contentView | |
}() | |
convenience init() { | |
self.init(axis: .vertical) | |
} | |
convenience init(axis: UILayoutConstraintAxis = .vertical) { | |
self.init(frame: .zero) | |
contentView.axis = axis | |
setup() | |
} | |
private lazy var verticalConstraints: [NSLayoutConstraint] = { | |
return [ | |
contentView.widthAnchor.constraint(equalTo: widthAnchor), | |
] | |
}() | |
private lazy var horizontalConstraints: [NSLayoutConstraint] = { | |
return [ | |
contentView.heightAnchor.constraint(equalTo: heightAnchor), | |
] | |
}() | |
private func setup() { | |
addSubview(contentView) | |
NSLayoutConstraint.activate([ | |
contentView.topAnchor.constraint(equalTo: topAnchor), | |
contentView.leadingAnchor.constraint(equalTo: leadingAnchor), | |
contentView.trailingAnchor.constraint(equalTo: trailingAnchor), | |
contentView.bottomAnchor.constraint(equalTo: bottomAnchor), | |
]) | |
} | |
override func updateConstraints() { | |
switch axis { | |
case .horizontal: | |
NSLayoutConstraint.deactivate(verticalConstraints) | |
NSLayoutConstraint.activate(horizontalConstraints) | |
case .vertical: | |
NSLayoutConstraint.deactivate(horizontalConstraints) | |
NSLayoutConstraint.activate(verticalConstraints) | |
} | |
alwaysBounceVertical = axis == .vertical | |
alwaysBounceHorizontal = axis == .horizontal | |
super.updateConstraints() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment