MLEmojiLabel.m计算宽度与高度不准

  • 内容
  • 评论
  • 相关

主要是换行模式问题

        messageLabel.lineBreakMode = NSLineBreakByCharWrapping;

其次

    // 打印更详细的属性信息
    NSAttributedString *attrText = self.attributedText;
    __block UIFont *textFont = self.font; // 默认使用self.font
    [attrText enumerateAttributesInRange:NSMakeRange(0, attrText.length)
                                options:0
                             usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
        NSLog(@"Range: %@ - Attributes: %@", NSStringFromRange(range), attrs);
        // 获取字体属性
        if ([attrs objectForKey:NSFontAttributeName]) {
            textFont = [attrs objectForKey:NSFontAttributeName];
        }
    }];
    
    // 检查文本内容
    NSLog(@"Text content: %@", attrText.string);
    
    // 创建新的AttributedString以确保属性正确
    NSMutableAttributedString *mutableText = [[NSMutableAttributedString alloc] initWithAttributedString:attrText];
    
    // 设置明确的段落样式
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping; // 强制使用按字符换行
    paragraphStyle.alignment = self.textAlignment;
    paragraphStyle.lineSpacing = self.lineSpacing;
    // 确保没有其他可能影响布局的段落属性
    paragraphStyle.headIndent = 0;
    paragraphStyle.firstLineHeadIndent = 0;
    paragraphStyle.tailIndent = 0;
    
    // 应用段落样式
    [mutableText addAttribute:NSParagraphStyleAttributeName
                       value:paragraphStyle
                       range:NSMakeRange(0, mutableText.length)];
    
    // 确保字体属性存在
    [mutableText addAttribute:NSFontAttributeName
                       value:textFont
                       range:NSMakeRange(0, mutableText.length)];
    
    // 临时设置新的AttributedText
    NSAttributedString *originalText = self.attributedText;
    self.attributedText = mutableText;
    
    // 计算大小
    CGSize maxSize = CGSizeMake(size.width - self.textInsets.left - self.textInsets.right,
                               CGFLOAT_MAX);
    CGSize rSize = [super sizeThatFits:maxSize];
    
    // 恢复原始文本
    self.attributedText = originalText;
    
    // 添加insets
    rSize.width += (self.textInsets.left + self.textInsets.right);
    rSize.height += (self.textInsets.top + self.textInsets.bottom);
    
    // 详细的日志输出
    NSLog(@"Font: %@", textFont);
    NSLog(@"ParagraphStyle: %@", paragraphStyle);
    NSLog(@"TextInsets: %@", NSStringFromUIEdgeInsets(self.textInsets));
    NSLog(@"Original size: %.1f x %.1f", size.width, size.height);
    NSLog(@"Max size (with insets): %.1f x %.1f", maxSize.width, maxSize.height);
    NSLog(@"Final size: %.1f x %.1f", rSize.width, rSize.height);
    
    return rSize;

评论

0条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注