在 UILabel iOS 中对齐文本
我遇到一个问题,在 iOS 中我使用 UILabel 显示 2,3 行文本,我想将文本对齐,但我没有找到任何选项来这样做。有什么建议如何使标签中的文本对齐吗?
我把这些线从顶部开始,
CGSize maximumSize = CGSizeMake(300, 9999);
NSString *textString = someString;
UIFont *textFont = [UIFont fontWithName:@"Futura" size:14];
CGSize textStringSize = [textString sizeWithFont:textFont
constrainedToSize:maximumSize
lineBreakMode:text.lineBreakMode];
CGRect textFrame = CGRectMake(10, 110, 300, textStringSize.height);
text.frame = textFrame;
所以像这样的任何技巧都可以使它变得合理 谢谢
I am having a problem that in iOS I am using UILabel to display 2,3 line text, I want to align text as justified but I am not finding any option to do so. Any suggestions how to make justify text in label?
i put these line to make start it from top
CGSize maximumSize = CGSizeMake(300, 9999);
NSString *textString = someString;
UIFont *textFont = [UIFont fontWithName:@"Futura" size:14];
CGSize textStringSize = [textString sizeWithFont:textFont
constrainedToSize:maximumSize
lineBreakMode:text.lineBreakMode];
CGRect textFrame = CGRectMake(10, 110, 300, textStringSize.height);
text.frame = textFrame;
so any trick like this to make it justfiy
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(5)
恐怕无法做到 - 好吧,用 UILabel 不行。
您可以使用 UIWebView 或第三方库,例如 OHAttributedLabel
快乐编码: )
更新:
这个答案自 iOS6 以来已过时。请参考Tankista的回答。
正如 @martin 提到的,我的类 OHAttributedLabel 可以非常轻松地做到这一点。
(你可以在我的 github 上找到它,也可以在 SO 上找到很多对它的引用)
这很容易完成,但你需要使用 Core Text。
子类化 UIView
,添加 NSString
属性,创建 NSAttributedString
并为 kCTParagraphStyleSpecifierAlignment 传递
键,然后在您的drawrect 方法中使用Quartz 或CoreText 绘制kCTJustifiedTextAlignment
值NSAttributedString
。
编辑:kCTParagraphStyleSpecifierAlignment
键kCTJustifiedTextAlignment
值应用于创建CTParagraphStyleRef
结构并作为kCTParagraphStyleAttributeName
的值传入创建 NSAttributedString
时的 key。
SWIFT 4.x
版本已批准的答案:
创建 NSMutableParagraphStyle 的实例并设置其属性。
let justifiedParagraphStyles: NSMutableParagraphStyle = NSMutableParagraphStyle.init() justifiedParagraphStyles.alignment = .justified //对齐文本 justifiedParagraphStyles.firstLineHeadIndent = 10.0 //必须有一个值才能使其工作
为文本属性创建 NSDictionary 并创建属性字符串。
让属性 = [NSAttributedStringKey.paragraphStyle: justifiedParagraphStyles] let attributeString = NSAttributedString.init(字符串: 字符串, 属性: 属性)
将属性字符串设置为标签。
existingLabel.attributedText = attributeString
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
从 iOS6 开始,现在有一种方便的方法来对齐文本。您可以创建 NSAttributedString 的实例,设置适当的属性并将此属性字符串分配给表示视图的文本,例如 UILabel、UITextView 等。很简单:
创建 NSMutableParagraphStyle 的实例并设置其属性。
为文本属性创建 NSDictionary 并创建属性字符串。
将属性字符串设置为标签。
There is now a convenient way to justify text since iOS6. You can create an instance of NSAttributedString, set appropriate properties and assign this attributed string to a text representing view such as UILabel, UITextView, etc. It's easy as this:
Create an instance of NSMutableParagraphStyle and set its properties.
Create NSDictionary for text attributes and create attributed string.
Set attributed string to a label.