Skip to content

Instantly share code, notes, and snippets.

@gk-plastics
Last active April 24, 2020 06:08
Show Gist options
  • Select an option

  • Save gk-plastics/a932ed4b51dcc28d891e33f08eb40259 to your computer and use it in GitHub Desktop.

Select an option

Save gk-plastics/a932ed4b51dcc28d891e33f08eb40259 to your computer and use it in GitHub Desktop.
UIImage extension that returns a SFSymbol image that matches to the specified font
extension UIImage {
static func symbol(named systemName: String, font: UIFont? = nil) -> UIImage? {
if #available(iOS 13.0, *) {
let image: UIImage?
if let font = font {
let symbolConfiguration = UIImage.SymbolConfiguration(font: font)
image = UIImage(systemName: systemName, withConfiguration: symbolConfiguration)
} else {
image = UIImage(systemName: systemName)
}
return image?.withRenderingMode(.alwaysTemplate)
} else {
return nil
}
}
}
// Example Usage:
let button = UIButton(type: .custom)
button.titleLabel?.font = UIFont.preferredFont(forTextStyle: .title1)
let buttonTitle = "Share"
let buttonImage = UIImage.symbol(named: "square.and.arrow.up", font: button.titleLabel?.font)
button.setTitle(buttonTitle, for: UIControl.State())
button.setImage(buttonImage, for: UIControl.State())
button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 10)
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: -5)
button.tintColor = button.titleLabel?.textColor
view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment