Created
July 17, 2019 03:35
-
-
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.
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
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