左右对齐具有“\ n”的标签。 [英] Align label from left and right that have "\n"
问题描述
我有一个带有这样文字的标签
I have one label with text like this
label.text = "A 34\nB 11\nC 4\nD 3"
它看起来像这样
A 34
B 11
C 5
D 3
有没有办法从左到右对齐标签所以它看起来像:
Is there a way to align label from left and right so it look like:
A 34
B 11
C 5
D 3
推荐答案
`你可以创建一个行类(自定义UIView)并让每个列元素(单独的UILabel)由用于填充的数据设置它。然后,您可以拥有一个表类,以便您可以使用最长的字符串并调整每列的位置。这种方法会给你很多控制,但额外的工作。
`You could make a row Class (custom UIView) and have each "column" element (separate UILabel) set by the data used to populate it. You could then have a table Class so that you could use the longest string and adjust the positioning of the each column. This approach would give you a lot of control, but extra work.
或者使用NSAttributedString和制表位。
Or use NSAttributedString with tab stops.
let myText = "A\t34\nB\t11\nC\t5\nD\t3"
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.tabStops = [NSTextTab(textAlignment: NSTextAlignment.Left, location: 150, options: [:])]
paragraphStyle.headIndent = 150
label.attributedText = NSAttributedString(string: text, attributes:[NSParagraphStyleAttributeName: paragraphStyle])
您可以计算循环中最长的字符串宽度,以确定 headIndent
应该是什么是。但是,这不允许右列在您的示例中右对齐。你会得到类似的东西:
You can calculate the longest string width in a loop to determine what the headIndent
should be. However, this wouldn't allow for the right column to be right-aligned like in your example. You would get something like:
A 34
B 11
C 5
D 3
这篇关于左右对齐具有“\ n”的标签。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!