Skip to content

Instantly share code, notes, and snippets.

@vinczebalazs
Created October 10, 2019 20:42
Show Gist options
  • Save vinczebalazs/1d2c1baf37d6b4edae4a52ccf468fd5a to your computer and use it in GitHub Desktop.
Save vinczebalazs/1d2c1baf37d6b4edae4a52ccf468fd5a to your computer and use it in GitHub Desktop.
final class ExpandableLabel: UILabel {
private let collapsedHeight: CGFloat = 65
private var heightConstraint: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
heightConstraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil,
attribute: .height, multiplier: 1, constant: collapsedHeight)
NSLayoutConstraint.activate([heightConstraint])
numberOfLines = 0
contentMode = .top
isUserInteractionEnabled = true
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(toggle)))
}
@objc private func toggle() {
if heightConstraint.constant > collapsedHeight {
heightConstraint.constant = collapsedHeight
} else {
heightConstraint.constant = sizeThatFits(CGSize(width: frame.size.width,
height: CGFloat.greatestFiniteMagnitude)).height
}
UIView.animate(withDuration: 0.25, animations: {
self.superview?.superview?.superview?.superview?.layoutIfNeeded()
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment