我的方法是将 CK 与 TTTAttributedLabel 结合起来。首先,我定义了一个结构,它包含一些我需要设置为 TTTAttributedLabel 的基本信息,
struct ABCKAttributeLabelData {
NSString *content;
UIFont *normalFont;
UIColor *normalColor;
UIFont *linkFont;
UIColor *linkColor;
NSInteger numberOfLines;
};
然后,我创建一个新类,命名为 CKComponent 的子类 ABCKAttributeLabelComponent,实现如下初始化方法:
+ (instancetype)newWithData:(ABCKAttributeLabelData)data {
ABCKAttributeLabelComponent *com =
[super newWithView:{
[TTTAttributedLabel class],
{
{@selector(setText:), [data.content attributedStringWithStyle:
@{NSForegroundColorAttributeName : data.normalColor,
NSFontAttributeName : data.normalFont,}]},
{@selector(setLinkAttributes:), @{ NSForegroundColorAttributeName : data.linkColor,
NSFontAttributeName : data.linkFont}},
{@selector(setActiveLinkAttributes:), @{ NSForegroundColorAttributeName : data.linkColor,
NSFontAttributeName : data.linkFont}},
{@selector(setNumberOfLines:), data.numberOfLines ?: 0},
{@selector(setLineBreakMode:), NSLineBreakByTruncatingTail},
}
} size:{}];
com.attributeString = [data.content attributedStringWithStyle:
@{NSForegroundColorAttributeName : data.normalColor,
NSFontAttributeName : data.normalFont,}];
com.normalFont = data.normalFont;
com.numOfLine = data.numberOfLines ?: 0;
return com
第三,计算 TTTAttributedLabel 的大小并返回。CK 将调用 computeLayoutThatFits: 方法来获取组件大小。所以覆盖它。
- (CKComponentLayout)computeLayoutThatFits:(CKSizeRange)constrainedSize {
// self.attributeString,self.numOfLine and self.normalFont I saved as property in initialize method
CGSize computerSize = [self.attributeString sizeLabelToFitToSize:constrainedSize.max numberLines:self.numOfLine font:self.normalFont];
return {
self,
constrainedSize.clamp({
CKCeilPixelValue(computerSize.width),
CKCeilPixelValue(computerSize.height)
}),
{}
};
}
剩下的就是使用 ABCKAttributeLabelComponent。
它可能不是很优雅,但它可以工作。