NSTextAlignment.Justified for UILabel不起作用 [英] NSTextAlignment.Justified for UILabel does not work

查看:459
本文介绍了NSTextAlignment.Justified for UILabel不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试证明我的UILabel文本是正确的,但是它不起作用.

I am trying to justify my UILabel text but it does not work.

我的UIView声明:

descriptionUIView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)

我的UILabel的声明:

bottleDescriptionLabel = UILabel(frame: CGRect(x: widthMargin, y: bottleDescriptionTitleLabel.frame.maxY + heightMargin, width: self.view.frame.width - (2 * widthMargin), height: heightBottleDescription - (2 * heightMargin)))
bottleDescriptionLabel.font = UIFont(name: "AvenirNext-Regular", size: 16)
bottleDescriptionLabel.text = bottleDescriptionString
bottleDescriptionLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
bottleDescriptionLabel.textAlignment = NSTextAlignment.Justified
bottleDescriptionLabel.numberOfLines = 0

它看起来像这样:

我不知道还可以使用该NSTextAlignment.Justified来为我的文字辩护.我应该改用UITextView吗?

I don't know what else to use that NSTextAlignment.Justified to justified my text. Should I use a UITextView instead?

推荐答案

您必须创建一个与NSAttributedString结合使用的NSMutableParagraphStyle,以便将文本显示为合理. 重要的部分是将NSBaselineOffsetAttributedName设置为0.0.

You have to create an NSMutableParagraphStyle in combination with an NSAttributedString in order to display text as justified. The important part is to set NSBaselineOffsetAttributedName to 0.0.

以下是如何将所有内容放在一起的示例:

Here's an example how to put everything together:

let sampleText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.Justified

let attributedString = NSAttributedString(string: sampleText,
    attributes: [
        NSParagraphStyleAttributeName: paragraphStyle,
        NSBaselineOffsetAttributeName: NSNumber(float: 0)
    ])

let label = UILabel()
label.attributedText = attributedString
label.numberOfLines = 0
label.frame = CGRectMake(0, 0, 400, 400)


let view = UIView()
view.frame = CGRectMake(0, 0, 400, 400)
view.addSubview(label)

NSBaselineOffsetAttributedName的信用: https://stackoverflow.com/a/19445666/2494219

Credits for NSBaselineOffsetAttributedName: https://stackoverflow.com/a/19445666/2494219

这篇关于NSTextAlignment.Justified for UILabel不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆