0

I'm trying to display some text in a UILabel using attributedText, with 2 different text alignments. I'm fetching the values from Firebase & they are key and value types. For some reason I can't get the title to be aligned left and the subtitle aligned right. Any help is appreciated.

 private func descriptionAttributedText() -> NSAttributedString {
    let title = "some title on the left side of the screen"
    let subtitle = "subtitle on the right side"

    let rightParagraph = NSMutableParagraphStyle()
    rightParagraph.alignment = .right

    let titleAttributes = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14), NSAttributedStringKey.foregroundColor: UIColor.black]
    let titleString = NSMutableAttributedString(string: title, attributes: titleAttributes)

    let subtitleAttributes = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 13), NSAttributedStringKey.foregroundColor: UIColor.darkGray, NSAttributedStringKey.paragraphStyle: rightParagraph]
    let subtitleString = NSAttributedString(string: subtitle, attributes: subtitleAttributes)

    let paragraph = NSMutableParagraphStyle()
    paragraph.setParagraphStyle(.default)
    paragraph.lineSpacing = 2

    let range = NSMakeRange(0, titleString.string.count)
    titleString.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraph, range: range)

    titleString.append(subtitleString)


    return titleString
}

The result I'm getting is of type "Titlesubtitle"

I have looked here, Attributed text with two text alignments, but it doesn't help me much.

I'm trying to get the same effect as on the App Store, but instead of

Seller ..................... Facebook Inc. , I'm getting

SellerFacebook Inc.

img_5752

r3dm4n
  • 1,175
  • 2
  • 18
  • 33
  • why you say they are not aligned? might you post what you get? – mugx Dec 15 '17 at 20:24
  • I've edited the question. – r3dm4n Dec 15 '17 at 20:41
  • I see, then you cannot solve the problem in that way (`NSAttributedString`). In the picture, there is probably a `UITableView` (might be also a custom `UIVIew`) with a `UITableViewCell` (talking about the first one) having 2 different `UILabel`. – mugx Dec 15 '17 at 20:46
  • This looks like standard *Right Detail* styled cells – vadian Dec 15 '17 at 21:00
  • 1
    Its best to make them separate UILabels – Andrew McKinley Dec 15 '17 at 23:45
  • This clearly seems to be two `UILabel`. It's easier. That's what I would STRONGLY suggest. But you can use this https://stackoverflow.com/questions/22617365/ios-multiple-right-and-left-align-on-same-line if you really want to use one single label, but that's overkill, and make this more complicated. – Larme Dec 16 '17 at 02:33

1 Answers1

0

I've solved the problem using the right detail styled cells as @vadian adivsed.

let cell = UITableViewCell(style: .value1, reuseIdentifier: "CellId")

Thanks !

r3dm4n
  • 1,175
  • 2
  • 18
  • 33