在做一个浮层滚动聊天的视图时,使用了MLEmojiLabel和TTTAttributedLabel这两个三方开源文件,遇到的问题就是:1、按照MLEmojiLabel的demo里将emojiLabel添加在tableView的contentView上后发现,emojiLabel总是会偏下大概5pt。2、随着文字增多偏下的程度越大并且计算出来的cell的高度偏高。
找了找三方文件中,找到这个地方:
- (CGRect)textRectForBounds:(CGRect)bounds
limitedToNumberOfLines:(NSInteger)numberOfLines
{
bounds = UIEdgeInsetsInsetRect(bounds, self.textInsets);
if (!self.attributedText) {
return [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
}
CGRect textRect = bounds;
// Calculate height with a minimum of double the font pointSize, to ensure that CTFramesetterSuggestFrameSizeWithConstraints doesn't return CGSizeZero, as it would if textRect height is insufficient.
textRect.size.height = MAX(self.font.lineHeight * MAX(2, numberOfLines), bounds.size.height);
// Adjust the text to be in the center vertically, if the text size is smaller than bounds
CGSize textSize = CTFramesetterSuggestFrameSizeWithConstraints([self framesetter], CFRangeMake(0, (CFIndex)[self.attributedText length]), NULL, textRect.size, NULL);
textSize = CGSizeMake(CGFloat_ceil(textSize.width), CGFloat_ceil(textSize.height)); // Fix for iOS 4, CTFramesetterSuggestFrameSizeWithConstraints sometimes returns fractional sizes
if (textSize.height < bounds.size.height) {
CGFloat yOffset = 0.0f;
switch (self.verticalAlignment) {
case TTTAttributedLabelVerticalAlignmentCenter:
yOffset = CGFloat_floor((bounds.size.height - textSize.height) / 2.0f);
break;
case TTTAttributedLabelVerticalAlignmentBottom:
yOffset = bounds.size.height - textSize.height;
break;
case TTTAttributedLabelVerticalAlignmentTop:
default:
break;
}
textRect.origin.y += yOffset;
}
return textRect;
}
这个地方根据verticalAlignment重新计算了emojiLabel的yOffset,使用TTTAttributedLabelVerticalAlignmentCenter和TTTAttributedLabelVerticalAlignmentBottom的话yOffset都会增加,这里没太多时间研究为什么TT要这么做,但是的确是这里导致的问题。
在MLEmojiLabel中修改两处:1、在计算cell高度的方法中,创建静态的emojiLabel时,使用emojiLabel.verticalAlignment = TTTAttributedLabelVerticalAlignmentTop;2、自己的cell里创建emojiLabel的时候也使用TTTAttributedLabelVerticalAlignmentTop。使用TTTAttributedLabelVerticalAlignmentTop就不再重新计算emojiLabel的yOffset。