Search code examples
iosswiftuitextviewnsattributedstring

Attributed text with two text alignments


Does anyone know how to achieve two different text alignments in one string?

This is what I want the textView to show:

label                                                                         value

My code:

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

What I get instead:

label value

Solution

  • Using NSMutableParagraphStyle with 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
    

    screenshot

    Of course, this aligns to "tabstop", but not to the edge of UITextView. When you modify the size of the view, you have to also modify the location of NSTextTab.