Skip to content

Instantly share code, notes, and snippets.

@grifas
Created October 1, 2018 16:19
Show Gist options
  • Save grifas/ff24c24c9a6038978a8f6c6473e353a7 to your computer and use it in GitHub Desktop.
Save grifas/ff24c24c9a6038978a8f6c6473e353a7 to your computer and use it in GitHub Desktop.
A button with an icon on top
import Foundation
class TopIconButton: UIButton {
var color: UIColor = Color.Green
private init(with color: UIColor) {
self.color = color
super.init(frame: .zero)
}
convenience init(color: UIColor) {
self.init(with: color)
tintColor = color
imageView?.contentMode = .scaleAspectFit
}
override init(frame: CGRect) {
super.init(frame: frame)
tintColor = color
imageView?.contentMode = .scaleAspectFit
}
override func layoutSubviews() {
super.layoutSubviews()
adjustImageAndTitleVertically()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func adjustImageAndTitleVertically() {
let spacing: CGFloat = 3
let titleSize: CGSize = titleLabel!.frame.size
let imageSize: CGSize = imageView!.frame.size
titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageSize.width, bottom: -(imageSize.height + spacing), right: 0)
imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + spacing), left: 0, bottom: 0, right: -titleSize.width)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment