简体   繁体   中英

Attributed text in swift with line alignment

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.

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]
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM