Last active
June 2, 2021 07:45
-
-
Save kyungpyoda/247f12817ae137bafe84c5e2512c5342 to your computer and use it in GitHub Desktop.
[Swift] iOS Implement Prefix Image String by using NSAttributedString
This file contains 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
// | |
// NSAttributedString+withPrefixImage.swift | |
// | |
// Created by 홍경표 on 2021/05/31. | |
// | |
import UIKit.UIImage | |
extension NSAttributedString { | |
/// "AttributedString with a prefix image" maker | |
/// - Parameters: | |
/// - prefixImage: a prefix image (will looks like an icon) | |
/// - text: some strings | |
/// - textAttributes: - [.font: UIFont.preferredFont(forTextStyle: .body), .foregroundColor: UIColor.black, ...] | |
convenience init(prefixImage: UIImage?, text: String, textAttributes: [NSAttributedString.Key : Any]?) { | |
let fullString = NSMutableAttributedString( | |
string: text, | |
// or string: "\( text)" for spacing | |
attributes: textAttributes | |
) | |
let height = fullString.size().height | |
if let prefixImage = prefixImage { | |
let imagePrefix = NSAttributedString( | |
attachment: NSTextAttachment().then { | |
$0.image = prefixImage | |
let ratio = prefixImage.size.width / prefixImage.size.height | |
$0.bounds = CGRect(x: $0.bounds.origin.x, y: $0.bounds.origin.y, width: ratio * height, height: height) | |
} | |
) | |
fullString.insert(imagePrefix, at: 0) | |
} | |
self.init(attributedString: fullString) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment