博客> 关于UILabel 显示多行文字的问题,label的最大显示还不够,怎么解决
关于UILabel 显示多行文字的问题,label的最大显示还不够,怎么解决
2019-11-13 09:31 评论:0 阅读:981 feng_zi
UIlabel UITextView 显示不够 多行显示 显示多行的各种设置

之前写的有关label显示多行的问题,但是经过个人反复测试,发下label显示的高度是有限制的,也就是说即使是多行显示,但是到一定高度就显示不了,显示内容为空,在此,为大家提供一种解决方法: 如果担心label显示的内容不够,就是用textView 来显示: NSString *content = [content2 stringByReplacingOccurrencesOfString:@"\n\n" withString:@"\n"];

    CGFloat width = self.view.frame.size.width-20.0f;
    //设置文本字体、段落等
    UIFont *font = [UIFont systemFontOfSize:20.0f];

    NSParagraphStyle *paragraphStyle = [self getParagraphStyle];
    NSMutableAttributedString *mAttrString = [[NSMutableAttributedString alloc] initWithString:content];
    [mAttrString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, content.length)];
    [mAttrString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, content.length)];

    //根据设置后的文本获取高度
    NSDictionary *attrs = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle};
    CGRect rect = [content boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                        options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                     attributes:attrs
                                        context:nil];

    textHeight = rect.size.height*1.08f;

    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(10.0f, contentHeight, width, textHeight)];
    textView.attributedText = mAttrString;
    [self.newsDetailScrollView addSubview:textView];
    textView.userInteractionEnabled = NO;

/* 设置段落 / 这里可以根据情况设置你想要的东西

  • (NSParagraphStyle )getParagraphStyle { NSMutableParagraphStyle mParagraphStyle = [[NSMutableParagraphStyle alloc] init]; mParagraphStyle.lineSpacing = 6.0f;//设置行间距 mParagraphStyle.paragraphSpacing = 15.0f;//段与段之间的间距 mParagraphStyle.alignment = NSTextAlignmentJustified;// 两端对齐的)文本对齐方式:(左,中,右,两端对齐,自然) mParagraphStyle.headIndent = 0;//整体缩进(首行除外) mParagraphStyle.tailIndent = 0; mParagraphStyle.firstLineHeadIndent = 0.0f;// 首行缩进 mParagraphStyle.minimumLineHeight = 10;//最低行高 mParagraphStyle.maximumLineHeight = 50;//最大行高 mParagraphStyle.lineBreakMode = NSLineBreakByWordWrapping; mParagraphStyle.baseWritingDirection = NSWritingDirectionNatural; mParagraphStyle.lineHeightMultiple = 0; mParagraphStyle.paragraphSpacingBefore = 0;//段首行空白空间 mParagraphStyle.hyphenationFactor = 0.5f;// 连字属性 在iOS,唯一支持的值分别为0和1 mParagraphStyle.defaultTabInterval = 100.0f; mParagraphStyle.allowsDefaultTighteningForTruncation = YES;

    // NSCharacterSet decimalTerminator = [NSCharacterSet characterSetWithCharactersInString:decimalFormatter.decimalSeparator]; // NSTextTab decimalTab = [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentCenter location:100 options:@{NSTabColumnTerminatorsAttributeName:decimalTerminator}];

    return [mParagraphStyle copy]; }

收藏
0
sina weixin mail 回到顶部