Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.