1

I'm trying to set my UILabels textAlignment to .right but it does not function at all. It's like it is not even there. Here is my code:

let productDescriptionLabel = UILabel(frame: CGRect(x: 10, y: imageViewHeight + productTitleLabel.frame.size.height + 10, width: viewWidth - 20, height: 0))
productDescriptionLabel.textColor = UIColor.darkGray
productDescriptionLabel.textAlignment = .right
productDescriptionLabel.text = productsDescriptionArray!
productDescriptionLabel.font = productDescriptionLabel.font.withSize(self.view.frame.height * self.relativeFontConstant)
productDescriptionLabel.numberOfLines = 0
let attrString = NSMutableAttributedString(string: productDescriptionLabel.text!)
let style = NSMutableParagraphStyle()
style.lineSpacing = 10
style.minimumLineHeight = 20
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: (productDescriptionLabel.text?.characters.count)!))
productDescriptionLabel.attributedText = attrString
productDescriptionLabel.sizeToFit()
productDescriptionLabel.lineBreakMode = .byWordWrapping
contentScrollView.addSubview(productDescriptionLabel)

All it shows is this

Winn Stone
  • 37
  • 4
  • 3
    Remove `productDescriptionLabel.textAlignment = .right` and instead `style.alignment = .right`? – Larme Oct 02 '17 at 07:36
  • You can do it with storyboard, check out may answer [here](https://stackoverflow.com/questions/45029041/text-align-last-css-property-swift-equivalent/45199912#45199912) – inspector_60 Oct 02 '17 at 08:02
  • @inspector_60 it would be useless for the OP case, he is using `NSMutableParagraphStyle` so that won't be applicable to the label. Please note that he already did what are you mentioned in your answer programmatically by implementing `productDescriptionLabel.textAlignment = .right`. I would suggest to check my posted answer :) – Ahmad F Oct 02 '17 at 08:04

1 Answers1

1

Since you are aiming to edit the label attributed string via a NSMutableParagraphStyle instance (style) , you should assign the desired alignment to your style, by editing the its alignment property:

style.alignment = .right

Also, because style handles the alignment, there is no need to implement:

productDescriptionLabel.textAlignment = .right
Ahmad F
  • 30,560
  • 17
  • 97
  • 143