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

63 lines
2.0 KiB
Swift
Raw Normal View History

2025-10-09 10:29:35 +00:00
//
// 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
}
}