[swift]归因于的文本与两个文本对齐方式

标签: UITextView ios Swift
发布时间: 2016/2/20 1:32:24
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

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

这是 textView 显示想要什么:

label                                                                         value

我的代码:

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

我得到了什么而是:

label value

任何帮助感谢!:)

解决方法 1:

使用 NSMutableParagraphStyleNSTextTab :

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

screenshot

当然,这将对齐到"制表位",但不是到边缘的 UITextView 。当您修改视图的大小时,您必须也修改 locationNSTextTab

官方微信
官方QQ群
31647020