【问题标题】:NSAttributedString end of first line indentNSAttributedString 首行缩进结尾
【发布时间】:2015-01-09 07:08:51
【问题描述】:

我想将NSAttributedString 中的第一行作为UITextView 从第一行右侧缩进。

所以NSParagraphStyle 中的firstLineHeadIndent 将从左边开始缩进第一行。我想做同样的事情,但从我的UITextView 的右边开始。

这是我希望文本换行方式的屏幕截图。

【问题讨论】:

  • 右边距是整篇文章?如果是,你应该看看tailIndentNSParagraphStyle
  • 不只是文本中的第一行。
  • 我建议两个NSParagraphStyle 所以。一个用于第一行(firstLineHeadIndent 和一个tailIndent,第二行用于文本的其余部分。但是第一行是否总是带有\n 的“第一行”?如果不是,您必须知道显示的第一行的范围。
  • 这是一个环绕行,它是 firstLineHeadIndent 缩进的内容。我想从右侧做同样的事情。
  • 您能否编辑您的问题以显示您想要的内容和您的实际代码?

标签: ios objective-c uitextview nsattributedstring


【解决方案1】:

Text System User Interface Layer Programming Guide 中的Setting Text Margins article 有这个图:

如您所见,没有内置机制可以让首行尾部缩进。

但是,NSTextContainer 有一个属性exclusionPaths,它表示应该排除文本的矩形区域的一部分。因此,您可以在右上角添加一条路径,以防止文本进入那里。

UIBezierPath* path = /* compute path for upper-right portion that you want to exclude */;
NSMutableArray* paths = [textView.textContainer.exclusionPaths mutableCopy];
[paths addObject:path];
textView.textContainer.exclusionPaths = paths;

【讨论】:

  • 你知道是否有一种方法可以右对齐排除路径吗?我的文本视图可以改变大小。
  • 据我所知。您需要监控视图的宽度变化,并删除您添加的排除路径,重新计算一个新路径并添加它。
【解决方案2】:

我建议创建 2 个不同的 NSParagraphStyle:一个特定于第一行,第二个用于文本的其余部分。

    //Creating first Line Paragraph Style
NSMutableParagraphStyle *firstLineStyle = [[NSMutableParagraphStyle alloc] init];
[firstLineStyle setFirstLineHeadIndent:10];
[firstLineStyle setTailIndent:200]; //Note that according to the doc, it's in point, and go from the origin text (left for most case) to the end, it's more a length that a "margin" (from right) that's why I put a "high value"
    //Read there: https://developer.apple.com/library/ios/documentation/Cocoa/Reference/ApplicationKit/Classes/NSMutableParagraphStyle_Class/index.html#//apple_ref/occ/instp/NSMutableParagraphStyle/tailIndent

    //Creating Rest of Text Paragraph Style
NSMutableParagraphStyle *restOfTextStyle = [[NSMutableParagraphStyle alloc] init];
[restOfTextStyle setAlignement:NSTextAlignmentJustified];
//Other settings if needed

    //Creating the NSAttributedString
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:originalString];
[attributedString addAttribute:NSParagraphStyleAttributeName value:firstLineStyle range:rangeOfFirstLine];
[attributedString addAttribute:NSParagraphStyleAttributeName
                         value:restOfTextStyle
                         range:NSMakeRange(rangeOfFirstLine.location+rangeOfFirstLine.length,
                                           [originalString length]-(rangeOfFirstLine.location+rangeOfFirstLine.length))];

    //Setting the NSAttributedString to your UITextView
[yourTextView setAttributedText:attributedString]; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    相关资源
    最近更新 更多