归因于两个文本对齐的文本

Whi*_*ter 4 uitextview nsattributedstring ios swift

有谁知道如何在一个字符串中实现两个不同的文本对齐?

这就是我想要textView显示的内容:

label                                                                         value
Run Code Online (Sandbox Code Playgroud)

我的代码:

let txtView = cell.viewWithTag(77) as! UITextView

let leftStyle = NSMutableParagraphStyle()
leftStyle.alignment = NSTextAlignment.Left
let rightStyle = NSMutableParagraphStyle()
rightStyle.alignment = NSTextAlignment.Right

let attText = NSMutableAttributedString(string: "label", attributes: [NSParagraphStyleAttributeName: leftStyle])
attText.appendAttributedString(NSAttributedString(string: " "))
attText.appendAttributedString(NSAttributedString(string: "value", attributes: [NSParagraphStyleAttributeName: rightStyle]))

txtView.attributedText = attText
Run Code Online (Sandbox Code Playgroud)

我得到的是:

label value
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏!:)

rin*_*aro 13

使用NSMutableParagraphStyle具有NSTextTab:

let paragraph = NSMutableParagraphStyle()
paragraph.tabStops = [
    NSTextTab(textAlignment: .Right, location: 100, options: [:]),
]

let str = "Label\tValue\n"
    + "foo\tbar\n"

let attributed = NSAttributedString(
    string: str,
    attributes: [NSParagraphStyleAttributeName: paragraph]
)

let view = UITextView(frame: CGRectMake(0, 0, 120, 120))
view.textContainer.lineFragmentPadding = 10

view.attributedText = attributed
Run Code Online (Sandbox Code Playgroud)

截图

当然,这与"tabstop"对齐,但不是与"tabstop"对齐UITextView.修改视图的大小时,还必须修改其中location的NSTextTab.

  • @SamB 100是`view.textContainer.size.width - view.textContainer.lineFragmentPadding*2`.这意味着文本区域的右边缘. (2认同)