iphone - objective-c - 文本缩进

标签 iphone ios objective-c uilabel core-text

这个问题是关于在 iOS 中实现文本缩进(“文本的位置更靠右以将其与周围的文本分开”)。

以下面的文字为例:

  1. 这是第一部分。
  2. 这是第二个,
    有两条线。
  3. 这是第三个。

请注意,第 2 部分中的第二行从更右边开始,就在上一行的下方。

我的代码包含一个 NSString 数组,每个都应该显示为一个带有数字项目符号的部分,如上所示。例如:

NSArray *array = [NSArray arrayWithObjects:@"1. This is the first section.", @"2. This is the second one, with two lines.", @"3. This is the third.", nil];

我使用 UILable 在屏幕上显示文本。
要将数组中的文本设置为标签,并在新行中分隔每个字符串,我使用

myLabel.text = [array componentsJoinedByString:@"\n"];

有什么想法可以实现这种效果吗?

最佳答案

在 iOS6 中,使用 - [UILabel setAttributedText:] 在某种程度上是可能的。

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.headIndent = 29;

myLabel.attributedText = [[NSAttributedString alloc] initWithString:
    @"1.\tShort line.\n2.\tLong line with content that triggers wrapping.\n3.\tShort line."
    attributes:@{NSParagraphStyleAttributeName: paragraphStyle}];

Result of the above code

这会在后续行中添加缩进。看起来 iOS 不像 OSX 那样支持制表位,所以我没有看到调整数字和文本之间差距的方法。这在 CoreText 中可能是可能的。

当然,您也可以只用 UIWebView 替换标签,并以性能为代价在所有版本的 iOS 上拥有完全的格式控制。

关于iphone - objective-c - 文本缩进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16240906/

相关文章:

objective-c - ReactiveCocoa 捕捉所有错误——对集合对象的异步网络操作

iphone - 如何在 Interface Builder 中创建以 UITableViewController 作为根的 UINavigationController?

iphone - 如何以编程方式创建此工具栏

ios - 何时将用户注册数据保存到 Cloud Firestore

ios - 针对区域本地化 iPhone 应用程序

ios - 堆内存的持久化分配 NSTimer

ios - UIView 将如何获得释放?解释

iphone - 使用核心数据iOS的登录ID和密码

iphone - 如何将数组中的数字从低到高排序

objective-c - iOS 应用程序可以访问设备视频库中视频的字幕或隐藏式字幕吗?