Created
April 22, 2020 15:30
-
-
Save gk-plastics/f4ad7c3f4ffec57003ea8e2e7b7a7107 to your computer and use it in GitHub Desktop.
UILabel extension that sets text prepended by a SF Symbols image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension UILabel { | |
func setText(_ text: String, prependedBySymbolNameed symbolSystemName: String, font: UIFont? = nil) { | |
if #available(iOS 13.0, *) { | |
if let font = font { self.font = font } | |
let symbolConfiguration = UIImage.SymbolConfiguration(font: self.font) | |
let symbolImage = UIImage(systemName: symbolSystemName, withConfiguration: symbolConfiguration)?.withRenderingMode(.alwaysTemplate) | |
let symbolTextAttachment = NSTextAttachment() | |
symbolTextAttachment.image = symbolImage | |
let attributedText = NSMutableAttributedString() | |
attributedText.append(NSAttributedString(attachment: symbolTextAttachment)) | |
attributedText.append(NSAttributedString(string: " " + text)) | |
self.attributedText = attributedText | |
} else { | |
self.text = text // fallback | |
} | |
} | |
} | |
// Usage: | |
// label.setText("Share", prependedBySymbolNameed: "square.and.arrow.up") // label is an instance of UILabel | |
// label.sizeToFit() // As needed | |
// Notes: | |
// When testing in a Swift Playground, place the extension code in a separate source file to avoid Xcode crash for an unknown reason (as of Xcode 11.4.1) | |
// Worked fine in a general application project. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment