Last active
August 3, 2022 21:17
-
-
Save IanKeen/f3c676dbad01cb2017b9328e1ad3487a to your computer and use it in GitHub Desktop.
BufferView - useful for custom padding in a stackview
This file contains 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 UIKit | |
class BufferView<Child: UIView>: UIView { | |
override var layoutMargins: UIEdgeInsets { | |
didSet { configure() } | |
} | |
override var isHidden: Bool { | |
didSet { configure() } | |
} | |
let view = Child() | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
configure() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
configure() | |
} | |
private func configure() { | |
view.removeFromSuperview() | |
if !isHidden { | |
addSubview(view) | |
applyConstraints(to: view) | |
} | |
} | |
private func applyConstraints(to view: UIView) { | |
view.translatesAutoresizingMaskIntoConstraints = false | |
NSLayoutConstraint.activate([ | |
view.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor), | |
view.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor), | |
view.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor), | |
view.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor), | |
]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment