Skip to content

Instantly share code, notes, and snippets.

@rjstelling
Created May 31, 2017 13:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjstelling/70c4d0ad6934df99246c0f56e3494f38 to your computer and use it in GitHub Desktop.
Save rjstelling/70c4d0ad6934df99246c0f56e3494f38 to your computer and use it in GitHub Desktop.
A simple Auto Layout solution for a UIButton with 2 labels.
class CustomButton: UIButton {
internal required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
internal override init(frame: CGRect) {
super.init(frame: frame)
}
}
class TwoLabelButton: CustomButton {
public let lhsTextLabel = UILabel(frame: .zero)
public let rhsTextLabel = UILabel(frame: .zero)
override var contentEdgeInsets: UIEdgeInsets {
didSet {
self.setNeedsLayout()
}
}
convenience init() {
self.init(frame: .zero)
self.addSubview(self.lhsTextLabel)
self.addSubview(self.rhsTextLabel)
self.lhsTextLabel.translatesAutoresizingMaskIntoConstraints = false
self.rhsTextLabel.translatesAutoresizingMaskIntoConstraints = false
}
override func layoutSubviews() {
super.layoutSubviews()
let lhsCenterV = NSLayoutConstraint(item: self.lhsTextLabel,
attribute: .centerY,
relatedBy: .equal,
toItem: self,
attribute: .centerY,
multiplier: 1.0,
constant: 0.0)
let rhsCenterV = NSLayoutConstraint(item: self.rhsTextLabel,
attribute: .centerY,
relatedBy: .equal,
toItem: self,
attribute: .centerY,
multiplier: 1.0,
constant: 0.0)
let lhsLeading = NSLayoutConstraint(item: self.lhsTextLabel,
attribute: .leadingMargin,
relatedBy: .equal,
toItem: self,
attribute: .leadingMargin,
multiplier: 1.0,
constant: self.contentEdgeInsets.left)
let rhsTrailing = NSLayoutConstraint(item: self.rhsTextLabel,
attribute: .trailingMargin,
relatedBy: .equal,
toItem: self,
attribute: .trailingMargin,
multiplier: 1.0,
constant: -self.contentEdgeInsets.right)
self.addConstraints([lhsCenterV, lhsLeading, rhsCenterV, rhsTrailing])
}
// MARK: - Convenience
public func setTitles(_ titleStrings: (String?, String?) = (nil, nil)) {
self.lhsTextLabel.text = titleStrings.0
self.rhsTextLabel.text = titleStrings.1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment