简体   繁体   English

Label 文字 alignment 多行

[英]Label Text alignment with multiple lines

I have a label with multiple lines.I want the text on the label always starts from top left corner independent of the height and number of lines of label.我有一个多行的 label。我希望 label 上的文本始终从左上角开始,与 label 的高度和行数无关。

Right now i am using a property现在我正在使用一个属性

[question1Label setContentMode: UIViewContentModeTopLeft];

But its not working但它不工作

Thanks谢谢

I've noticed that contentMode property of UILabel doesn't affect its text's alignment.我注意到UILabelcontentMode属性不会影响其文本的 alignment。 Use the textAlignment property.使用textAlignment属性。

label.textAlignment = UITextAlignmentLeft; 

Edit: This will align the text Center-Left.编辑:这将对齐文本左中。 In order to show the text from Top-Left you need to find the height of the text using sizeWithFont: method of NSString .为了从左上角显示文本,您需要使用NSStringsizeWithFont:方法找到文本的高度。 See this SO post to know how to do it. 请参阅此 SO 帖子以了解如何操作。

As an alternative you can use UITextField , the subclass of UIControl , which inherits UIControl's the contentVerticalAlignment property.作为替代方案,您可以使用 UIControl 的子类UITextField ,它继承了UIControlcontentVerticalAlignment属性。

textField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;

You can use this property to align the text on top.您可以使用此属性来对齐顶部的文本。 You can disable the user from editing the text by using the property userInteractionEnabled property.您可以使用属性userInteractionEnabled属性禁止用户编辑文本。

The accepted answer no longer worked for me as UITextAlignmentLeft has been depreciated.由于 UITextAlignmentLeft 已被贬值,因此接受的答案不再适用于我。

The following works great!以下效果很好!

// Allow multiline label centered
[label setNumberOfLines:0];
[label setTextAlignment:NSTextAlignmentCenter];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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