在UITextView内画一条线-NSAttributedString

lostInTransit

我希望在UITextView由一些文本组成的内部绘制一条可自定义的线(使用NSAttributedString

这是我尝试过的

NSString *unicodeStr = [NSString stringWithFormat:@"%C%C%C", 0x00A0, 0x0009, 0x00A0]; //nbsp, tab, nbsp
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:unicodeStr];
NSRange strRange = NSMakeRange(0, str.length);

NSMutableParagraphStyle *const tabStyle = [[NSMutableParagraphStyle alloc] init];
tabStyle.headIndent = 16; //padding on left and right edges
tabStyle.firstLineHeadIndent = 16;
tabStyle.tailIndent = -16;
NSTextTab *listTab = [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentCenter location:40 options:@{}]; //this is how long I want the line to be
tabStyle.tabStops = @[listTab];
[str  addAttribute:NSParagraphStyleAttributeName value:tabStyle range:strRange];
[str addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInt:2] range:strRange];

但是,无论我为制表符停止位置(在这种情况下为40)还是tailIndent(在此为-16)提供什么值,该行仅尊重headIndent并跨越整个UITextView宽度(当然要减去headIndent)。

编辑-我很确定问题是因为我没有使用正确的Unicode字符(尽管它们似乎是逻辑选择)。万一这给别人一个提示,如果我在第二个nbsp之后添加一个空格,即朝末尾添加一个空格,则制表符将限制为单个制表符长度

布布

是您的预期结果吗?

在此处输入图片说明 在此处输入图片说明

你可以尝试一下:

NSTextTab *listTab = [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentCenter location:self.textView.frame.size.width - tabStyle.firstLineHeadIndent + tabStyle.tailIndent options:@{}];

这是完整的代码:

- (void) viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];
  NSString *unicodeStr = @"\n\u00a0\t\t\n";
  NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:unicodeStr];
  NSRange strRange = NSMakeRange(0, str.length);

  NSMutableParagraphStyle *const tabStyle = [[NSMutableParagraphStyle alloc] init];
  tabStyle.headIndent = 16; //padding on left and right edges
  tabStyle.firstLineHeadIndent = 16;
  tabStyle.tailIndent = -70;
  NSTextTab *listTab = [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentCenter location:self.textView.frame.size.width - tabStyle.headIndent + tabStyle.tailIndent options:@{}]; //this is how long I want the line to be
  tabStyle.tabStops = @[listTab];
  [str  addAttribute:NSParagraphStyleAttributeName value:tabStyle range:strRange];
  [str addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInt:2] range:strRange];

  NSAttributedString *htmlStr = [[NSAttributedString alloc] initWithData:[@"<h1>Lorem ipsum dolor sit er elit lamet</h1>" dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];

  [str insertAttributedString:htmlStr atIndex:0];
  [str appendAttributedString:htmlStr];

  self.textView.attributedText = str;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章