Skip to content

Instantly share code, notes, and snippets.

@bleft
Last active March 12, 2021 19:04
Show Gist options
  • Save bleft/a1a7a39c3f90edefc5644369f918a74e to your computer and use it in GitHub Desktop.
Save bleft/a1a7a39c3f90edefc5644369f918a74e to your computer and use it in GitHub Desktop.
UIButton with centered Image and Text
// with the help of: https://gist.github.com/phpmaple/9458264
extension UIButton {
func centerImageAndButton(_ gap: CGFloat, imageOnTop: Bool) {
guard let imageView = self.imageView,
let titleLabel = self.titleLabel else { return }
let sign: CGFloat = imageOnTop ? 1 : -1;
let imageSize = imageView.frame.size;
self.titleEdgeInsets = UIEdgeInsetsMake((imageSize.height+gap)*sign, -imageSize.width, 0, 0);
let titleSize = titleLabel.bounds.size;
self.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height+gap)*sign, 0, 0, -titleSize.width);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment