【问题标题】:How to format a string for proper display in ios如何格式化字符串以在 ios 中正确显示
【发布时间】:2014-10-24 04:56:35
【问题描述】:

我的应用中有一个常见问题解答部分,但我必须使用不可编辑的 UITextView 以某种方式呈现它。就像下面一样,

  1. 如何取消录制?

    A.您可以在录制过程中按取消(红色“X”)按钮取消录制

      in the center of the speaker on the recording screen. The audio recording 
      will not be saved. 
    

但问题是你可以看到必须用一些填充来显示,下一行应该从答案行“不低于A”的下方开始。而且有大量的问题文档,所以我无法手动格式化。它适用于 iPhone 和 iPad,所以我的 UITextView 宽度不同。这类问题有解决办法吗?

【问题讨论】:

  • 我不太确定,但可以试试@"First line\n\tSecond Line with tab\n\t\tThird line with two tab"之类的选项卡。所以“\t”是一个制表符,“\n”是换行符
  • @DavidG。起初我是这么想的,但是 UITextView 的宽度出现在图片中,这对于 iphone 和 ipad 都是不同的。所以我不能用那个。

标签: ios nsstring uitextview string-formatting


【解决方案1】:

我建议使用NSAttributedStringNSParagraphStyle 结合NSParagraphAttributeName

这是一个例子:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:yourString];

int indent1 = 0;
int indent2 = 20;
int indent3 = 2*indent2;

NSMutableParagraphStyle *styleTitleByNumber = [[NSMutableParagraphStyle alloc] init];
[styleTitleByNumber setFirstLineHeadIndent:indent1];
[styleTitleByNumber setHeadIndent:indent1];

NSMutableParagraphStyle *styleTitleByLetter = [[NSMutableParagraphStyle alloc] init];
[styleTitleByLetter setFirstLineHeadIndent:indent2];
[styleTitleByLetter setHeadIndent:indent2];

NSMutableParagraphStyle *styleSimpleText = [[NSMutableParagraphStyle alloc] init];
[styleSimpleText setFirstLineHeadIndent:indent3];
[styleSimpleText setHeadIndent:indent3];

[attributedString addAttribute:NSParagraphStyleAttributeName 
                         value:styleTitleByNumber
                         range:rangeOfTitleByNumber];
[attributedString addAttribute:NSParagraphStyleAttributeName 
                          value:styleTitleByLetter 
                          range:rangeOfTitleByLetter];
[attributedString addAttribute:NSParagraphStyleAttributeName 
                          value:styleSimpleText
                          range:rangeOfSimpleText];

[yourTextView setAttributedText:attributedString];

现在,根据您的初始文本的格式,我让您知道在哪里应用哪种样式(对于 NSRange 参数),或者您也可以,如果不同的部分分开,则直接影响NSAttributedString,然后将它们全部合并。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 2017-09-25
    • 2012-05-12
    • 2019-08-21
    • 2014-09-22
    • 2011-07-12
    • 2019-08-06
    相关资源
    最近更新 更多