1

I have a label that has attributed text. I want to achieve something look like this image. sample label

Subcategory and price text should be left and right alignment respectively and in a single line. There is some space before Subcategory text. Please provide any sample code for this kind of attributed text.

Community
  • 1
  • 1
WAHID MARUF
  • 51
  • 1
  • 8
  • I tried to append text as new line but cannot append text as left and right alignment text in a single line. – WAHID MARUF Dec 05 '17 at 07:04
  • Can you do this in a table view. That will be much easier. – Sweeper Dec 05 '17 at 07:09
  • this label is actually in a table view cell. – WAHID MARUF Dec 05 '17 at 07:10
  • Possible duplicate of [NSMutableAttributedString add different alignments](https://stackoverflow.com/questions/16737503/nsmutableattributedstring-add-different-alignments) – Larme Dec 05 '17 at 07:24
  • Or https://stackoverflow.com/questions/22617365/ios-multiple-right-and-left-align-on-same-line But if it's a cell, clearly two UILabel would be easier and faster. – Larme Dec 05 '17 at 07:24

2 Answers2

2

I think you need to use a paragraph style and add a head indent.

let style = NSMutableParagraphStyle()
style.headIndent = 100 // your value here

Then add the paragraph style as the attribute.

[NSParagraphStyleAttributeName : style]

Swift 4 & 5

[NSAttributedString.Key.paragraphStyle : style]
Wendy Liga
  • 634
  • 5
  • 12
koropok
  • 1,393
  • 13
  • 19
0
let myLabelWidth = 300
let myLabelHeight = 50

let paragraph = NSMutableParagraphStyle()
paragraph.tabStops = [
    NSTextTab(textAlignment: .right, location: CGFloat(myLabelWidth), options: [:]),
]

let attributed = NSAttributedString(
    string: "Subcategory 1\t$30",
    attributes: [NSAttributedStringKey.paragraphStyle: paragraph]
)

// Change 'x' value to "some" space before the text
let myLabel = UILabel(frame: CGRect(x: 0,
                                    y: 0,
                                    width: myLabelWidth,
                                    height: myLabelHeight))

// Just added to see boundaries of the view that contains the text
myLabel.backgroundColor = UIColor.lightGray
myLabel.attributedText = attributed
Dorukhan Arslan
  • 2,676
  • 2
  • 24
  • 42