ios – 在UITextView – NSAttributedString中绘制一条线

前端之家收集整理的这篇文章主要介绍了ios – 在UITextView – NSAttributedString中绘制一条线前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望在包含一些文本的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字符(尽管它们似乎是合乎逻辑的选择).如果这给某人一个提示,如果我在第二个之后添加一个空格,即朝向末尾,则标签仅限于一个标签长度

解决方法@H_502_12@
这是你的预期结果吗?


你能试试这个:

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;
}

原文链接:https://www.f2er.com/iOS/334029.html

猜你在找的iOS相关文章