63 lines
2.0 KiB
Swift
63 lines
2.0 KiB
Swift
|
|
//
|
|||
|
|
// AttributeString.swift
|
|||
|
|
// Crush
|
|||
|
|
//
|
|||
|
|
// Created by Leon on 2025/8/26.
|
|||
|
|
//
|
|||
|
|
|
|||
|
|
/// 业务经常用到的一些AttributeString生成方法
|
|||
|
|
extension NSAttributedString{
|
|||
|
|
|
|||
|
|
/// 图片+文字的AttribueString。默认黑色vip+黑色文字
|
|||
|
|
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
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
}
|