Visual_Novel_iOS/crush/Crush/Src/Utils/Extensions/AttributeString.swift

63 lines
2.0 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// AttributeString.swift
// Crush
//
// Created by Leon on 2025/8/26.
//
/// AttributeString
extension NSAttributedString{
/// +AttribueStringvip+
static func getIconTitleAttributeByWords(
words: String,
icon: IconCode? = nil,
iconImage: UIImage? = nil,
iconSize: CGSize = CGSize(width: 24, height: 24),
iconColor: UIColor = .black,
textFont: UIFont = .t.tbsl,
textColor: UIColor = .black
) -> NSAttributedString {
let attributedString = NSMutableAttributedString()
// icon NSTextAttachment
func makeAttachment(with image: UIImage) -> NSAttributedString {
let attachment = NSTextAttachment()
attachment.image = image
// 使线
let yOffset = (textFont.capHeight - iconSize.height) / 2
attachment.bounds = CGRect(
x: 0,
y: yOffset,
width: iconSize.width,
height: iconSize.height
)
return NSAttributedString(attachment: attachment)
}
// 1. image
if let customImage = iconImage {
attributedString.append(makeAttachment(with: customImage))
}
// 2. 使 iconFont image
else if let iconCode = icon, let fontImage = MWIconFont.image(fromIcon: iconCode, size: iconSize, color: iconColor) {
attributedString.append(makeAttachment(with: fontImage))
}
// 3.
let text = " \(words)"
let textAttributedString = NSAttributedString(
string: text,
attributes: [
.font: textFont,
.foregroundColor: textColor
]
)
attributedString.append(textAttributedString)
return attributedString
}
}