带标签的 NSAttributedString [英] NSAttributedString with tabs

查看:46
本文介绍了带标签的 NSAttributedString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用这种文本格式创建 UILabel ?你会使用 NSAttributedString 吗?

解决方案

NSAttributedString 可以创建带有制表位的文本列.这与在具有相同限制的文字处理器中完成的方式类似.

let text = "Name\t: Johny\nGender\t: Male\nAge\t: 25\nFavourites\t: Reading,writing"让段落样式 = NSMutableParagraphStyle()段落样式.tabStops = [NSTextTab(textAlignment: NSTextAlignment.Left, location: 150, options: [:])]段落样式.headIndent = 150label.attributedText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName:paragraphStyle])

<块引用>

tabStops 提供点位置,用于在每个选项卡后继续文本的位置.在这里,我们在第一列之后的合理位置做了一个选项卡.headIndent 告诉标签换行的文本需要缩进一个固定的数量,所以它换行到下一行.

这种方法的局限性是:

  1. 制表位位置是一个固定点值,因此您需要知道自己想要什么.如果您选择的值小于某些行的第一列的宽度,这些行将缩进到不同的位置.
  2. 仅当您的最后一列是换行时,换行才真正有效.由于您的第二列以:"开头,因此您可能只想增加 headIndent 或将:"拆分为 \t:\t 并设置上第二个制表位.如果您不让文本换行,这不是问题.

如果这些限制过于严格,您可以将标签重组为具有自动布局约束的多个标签的集合.

How do you create a UILabel with this kind of text format? Would you use NSAttributedString?

解决方案

NSAttributedString can create text columns with tab stops. This is similar to how it is done in a word processor with the same limitations.

let text = "Name\t: Johny\nGender\t: Male\nAge\t: 25\nFavourites\t: Reading, writing"

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.tabStops = [NSTextTab(textAlignment: NSTextAlignment.Left, location: 150, options: [:])]
paragraphStyle.headIndent = 150

label.attributedText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName: paragraphStyle])

tabStops provides point positions for where to continue text after each tab. Here we did one tab at a reasonable point after the first column. headIndent tells the label that wrapped text needs to be indented by a fixed amount, so it wraps to the next line.

The limitations with this approach are:

  1. The tab stop location is a fixed point value so you need to know what you want. If the value you pick is less than the width of the first column for some lines, those lines will indent to a different location.
  2. Wrapping only really works if your last column is the one that wraps. Since your second column was prefaced by ":" You may want to either just increase your headIndent or also split out the ":" to be \t:\t and set up a second tab stop. If you're not letting text wrap, this is not an issue.

If these limitations are too restrictive, you can restructure your label to be a collection of multiple labels with auto layout constraints.

这篇关于带标签的 NSAttributedString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆