Swift 3:文本对齐失败



我正在尝试将我的UILabel的文本定位设置为 .right,但根本不起作用。就像它甚至没有。这是我的代码:

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)

它所显示的只是这个

由于您的目标是通过NSMutableParagraphStyle实例(style)编辑属性字符串的标签,因此您应通过编辑其alignment属性:

来将所需的对齐分配给您的style
style.alignment = .right

另外,由于style处理对齐方式,因此无需实现:

productDescriptionLabel.textAlignment = .right

最新更新