笔者在开发app过程中,有很多页面都需要富文本显示,因为写的重复代码太多,并且富文本的api和参数相对较多,不利于记忆,所以有必要将富文本的业务逻辑封装起来,方便以后开发过程中的调用。另外,这种造轮子方式都是逐步完善的,出现新的需求或问题,需要开发者不断地更新轮子。在此,笔者只是提供一个简单的思路,希望能给读者朋友一些小小的帮助。
封装字体的模型FRTextModel
FRTextModel模型封装了富文本相关的属性,例如文字、字体大小、字体颜色、行间距等,如下代码所示,
import UIKit
struct FRTextFontModel {
var text = ""
var fontSize: CGFloat = 0
var fontColor = UIColor.white
var lineSpacing: CGFloat = 0
}
构建富文本的核心类FRAttributesHelper
FRAttributesHelper将多个FRTextModel的内容拼接起来,并返回一个新的富文本字符串,如下代码所示,
import UIKit
class FRAttributesHelper: NSObject {
class func createAttributeText(models: [FRTextFontModel]) -> NSAttributedString {
var fullText: String = ""
for model in models {
fullText += model.text
}
let attributedString = NSMutableAttributedString(string: fullText)
var index: Int = 0
for model in models {
var attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: model.fontSize),
NSForegroundColorAttributeName: model.fontColor]
if model.lineSpacing != 0 {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = model.lineSpacing
attributes += [NSParagraphStyleAttributeName: paragraphStyle]
}
attributedString.addAttributes(attributes, range: NSRange(location: index, length: model.text.length))
index += model.text.length
}
return attributedString
}
}
简单的使用
使用非常简单,只需要构建FRTextModel内容,并以数组的形式传递给FRAttributesHelper的createAttributeText
类方法即可,如下代码所示,
// 设置数字的字体和颜色
let answerCount = FRTextFontModel(text: "\(model.answerCount)", fontSize: 18, fontColor: UIColor(hex: 0x333333), lineSpacing: 0)
let answerDesc = FRTextFontModel(text: " 个问题", fontSize: 11, fontColor: UIColor(hex: 0x666666), lineSpacing: 0)
self.questionCountLabel.attributedText = FRAttributesHelper.createAttributeText(models: [answerCount, answerDesc])
let postCount = FRTextFontModel(text: "\(model.postCount)", fontSize: 18, fontColor: UIColor(hex: 0x333333), lineSpacing: 0)
let postDesc = FRTextFontModel(text: " 个帖子", fontSize: 11, fontColor: UIColor(hex: 0x666666), lineSpacing: 0)
self.postCountLabel.attributedText = FRAttributesHelper.createAttributeText(models: [postCount, postDesc])
let bestAnswerCount = FRTextFontModel(text: "\(model.bestAnswerCount)", fontSize: 18, fontColor: UIColor(hex: 0x333333), lineSpacing: 0)
let bestAnswerDesc = FRTextFontModel(text: " 个最佳回答", fontSize: 11, fontColor: UIColor(hex: 0x666666), lineSpacing: 0)
self.bestAnswerCountLabel.attributedText = FRAttributesHelper.createAttributeText(models: [bestAnswerCount, bestAnswerDesc])
运行效果如下图所示,
attributes-text.jpeg
网友评论