Skip to content

Instantly share code, notes, and snippets.

@alexiscn
Last active September 16, 2022 10:54
Show Gist options
  • Save alexiscn/b1b97c11d0c79593f9d9cb99ceb844a4 to your computer and use it in GitHub Desktop.
Save alexiscn/b1b97c11d0c79593f9d9cb99ceb844a4 to your computer and use it in GitHub Desktop.
iOS Button ImageView and titleLabel align vertically center
import UIKit
extension UIButton {
func alignVerticalCenter(padding: CGFloat = 7.0) {
guard let imageSize = imageView?.frame.size, let titleText = titleLabel?.text, let titleFont = titleLabel?.font else {
return
}
let titleSize = (titleText as NSString).size(withAttributes: [.font: titleFont])
print(titleSize)
let total = imageSize.height + titleSize.height + padding
imageEdgeInsets = UIEdgeInsets(top: -(total - imageSize.height), left: 0, bottom: 0, right: -titleSize.width)
titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageSize.width, bottom: -(total - titleSize.height), right: 0)
}
}
@devAshirov
Copy link

it is not perfect

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment