首页 > 解决方案 > 中文和附件的情况下,UITextView的第一行表头被部分剪掉了

问题描述

我发现了一个奇怪的问题,UITextView 在某些条件下,header 会被剪掉一小部分。
如下所示。
header 会被剪掉一小部分
如果第一行全是中文,第二行有 NSAttachment,head 会被剪掉一点。
但是如果第一行全是英文或者中文中穿插了空格等符号,就会恢复正常。
英文全
是正常的 插入空格是正常的

我真的对这种现象感到困惑。这是iOS UITextView 对中文的特殊处理吗?如果我把 UITextView 改成 UILabel 就没有问题
了 这是我的示例代码。

    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 200, 336, 100)];
    textView.textContainer.lineFragmentPadding = 0;
    textView.textContainerInset = UIEdgeInsetsZero;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 400, 336, 100)];
    label.numberOfLines = 0;
    
    // Chinese init
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:@"哈哈哈哈哈哈哈哈哈哈哈哈"];
    // English init
    // NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:@"QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm"];
    [attributeStr addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} range:NSMakeRange(0, attributeStr.length)];
    
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.bounds = CGRectMake(0, 0, 16, 16);
    [attributeStr appendAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];
    
    NSMutableAttributedString *tailStr = [[NSMutableAttributedString alloc] initWithString:@"尾部"];
    [tailStr addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} range:NSMakeRange(0, tailStr.length)];
    [attributeStr appendAttributedString:tailStr];
    
    textView.attributedText = attributeStr;
    label.attributedText = attributeStr;
    [textView sizeToFit];
    [label sizeToFit];
    [self.view addSubview:label];
    [self.view addSubview:textView];

标签: iosuitextviewcjk

解决方案


推荐阅读