Skip to content

Instantly share code, notes, and snippets.

@pai911
Created July 17, 2019 03:35
Show Gist options
  • Save pai911/7887068f5df8deeb8a36eade2dbc253d to your computer and use it in GitHub Desktop.
Save pai911/7887068f5df8deeb8a36eade2dbc253d to your computer and use it in GitHub Desktop.
An extension to help center image and title in UIButton. The position of the image and title can be reversed.
extension UIButton {
func alignHorizontal(spacing: CGFloat, imageFirst: Bool) {
let edgeOffset = spacing / 2
imageEdgeInsets = UIEdgeInsets(top: 0,
left: -edgeOffset,
bottom: 0,
right: edgeOffset)
titleEdgeInsets = UIEdgeInsets(top: 0,
left: edgeOffset,
bottom: 0,
right: -edgeOffset)
if !imageFirst {
self.transform = CGAffineTransform(scaleX: -1, y: 1)
imageView?.transform = CGAffineTransform(scaleX: -1, y: 1)
titleLabel?.transform = CGAffineTransform(scaleX: -1, y: 1)
}
// increase content width to avoid clipping
contentEdgeInsets = UIEdgeInsets(top: 0, left: edgeOffset, bottom: 0, right: edgeOffset)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment