【问题标题】:How to align UILabel text in paragraph如何在段落中对齐 UILabel 文本
【发布时间】:2016-03-10 05:20:24
【问题描述】:

我在根据客户要求设置文本对齐时遇到了一个小问题。客户希望文本以段落方式与单独行中的数字对齐。请看下图,该数字有 19 像素的内边距,文本以段落方式对齐,内边距为 41 像素。

如果我们将左对齐设置为标签,我们将得到数字下方的第二行。

我尝试搜索解决方案但无法成功。

提前致谢。

【问题讨论】:

    标签: ios objective-c iphone uilabel


    【解决方案1】:

    您需要为问题部分和答案部分设置不同的属性。您已经这样做是为了控制字体,所以它不应该是一个大的变化。您需要为每个部分设置段落样式。对于问题部分,您需要将firstLineHeadIndent 设置为19,将headIndent 设置为41。对于答案部分,您需要将两者都设置为41。

    NSMutableParagraphStyle *questionStyle = [[NSMutableParagraphStyle alloc] init];
    questionStyle.firstLineHeadIndent = 19;
    questionStyle.headIndent = 41;
    NSDictionary *questionAttributes = @{
        NSParagraphStyleAttributeName: questionStyle,
        NSFontAttributeName: [UIFont systemFontOfSize: 20]
    };
    
    NSMutableParagraphStyle *answerStyle = [questionStyle mutableCopy];
    answerStyle.firstLineHeadIndent = questionStyle.headIndent;
    NSDictionary *answerAttributes = @{
        NSParagraphStyleAttributeName: answerStyle,
        NSFontAttributeName: [UIFont systemFontOfSize: 16]
    };
    
    NSMutableAttributedString *richText = [[NSMutableAttributedString alloc] init];
    [richText appendAttributedString:[[NSAttributedString alloc]
         initWithString:questionText attributes:questionAttributes]];
    [richText appendAttributedString:[[NSAttributedString alloc]
        initWithString:answerText attributes:answerAttributes]];
    
    label.attributedText = richText;
    

    【讨论】:

      【解决方案2】:

      一种可能性:

      • 使用带有自定义 NSParagraphStyle 的 NSAttributedString。第一行缩进可以与其他行不同(左边距)。

      另一种可能性:

      • 使用网络视图。您所描述的内容很容易使用 CSS 进行配置。

      【讨论】:

      • 你好,matt,你可以为我添加示例代码 sn-p 吗?这对我很有帮助。
      【解决方案3】:

      试试这个

      NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
      paragraphStyle.alignment = NSTextAlignmentLeft;
      [self.titleString drawWithRect:CGRectMake(xOffset, yOffset, titleLabelSize.width, titleLabelSize.height)
                                     options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine
                                  attributes:@{ NSParagraphStyleAttributeName:paragraphStyle}
                                     context:nil];
      

      【讨论】:

      • 您好 kiran 感谢您的回复,但我无法用上面的代码完全满足我的要求,请您编辑代码并提供一些示例文本 sn-p 和屏幕截图,这对我很有帮助
      猜你喜欢
      • 2012-09-16
      • 1970-01-01
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多