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)
}
}
@alexiscn
Copy link
Author

alexiscn commented Dec 18, 2018

How to use it.

let button = UIButton(type: .custom)
button.backgroundColor = .red
button.frame = CGRect(x: 30, y: 30, width: 80, height: 80)
button.setTitle("{Your_Title}", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
button.setImage(UIImage(named: "{YOUR_IMAHE_NAME}"), for: .normal)
button.setTitleColor(.white, for: .normal)

button. alignVerticalCenter()

@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