Skip to content

Instantly share code, notes, and snippets.

@clayellis
Last active May 15, 2017 19:07
Show Gist options
  • Save clayellis/5394d087e63161c2b42ad1c9ded6dc25 to your computer and use it in GitHub Desktop.
Save clayellis/5394d087e63161c2b42ad1c9ded6dc25 to your computer and use it in GitHub Desktop.
//
// UIButton+Extras.swift
// Clay Ellis
// https://gist.github.com/clayellis/5394d087e63161c2b42ad1c9ded6dc25
//
import UIKit
extension UIButton {
/// Set the button's background color for a control state
public func setBackgroundColor(_ color: UIColor, forUIControlState state: UIControlState) {
self.setBackgroundImage(UIImage(color: color), for: state)
}
public func alignImageRight(withPadding padding: CGFloat) {
guard let titleLabel = titleLabel, let imageView = imageView, let image = imageView.image else { return }
let titleWidth = titleLabel.intrinsicContentSize.width
let imageInset = titleWidth + padding
let imageWidth = image.size.width
imageEdgeInsets = UIEdgeInsets(top: 0, left: imageInset, bottom: 0, right: -imageInset)
titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageWidth, bottom: 0, right: imageWidth)
contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: padding)
}
func alignImageLeft(withPadding padding: CGFloat) {
guard let imageView = imageView, let image = imageView.image else { return }
let imageWidth = image.size.width
let leftToImageLeft = imageView.frame.minX
let gap = leftToImageLeft - padding
imageEdgeInsets = UIEdgeInsets(top: 0, left: -gap, bottom: 0, right: gap)
titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageWidth / 2, bottom: 0, right: imageWidth / 2)
}
func centerContents(withSpacing spacing: CGFloat) {
imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: spacing)
titleEdgeInsets = UIEdgeInsets(top: 0, left: spacing, bottom: 0, right: 0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment