xcode NSMutableAttributedString 的自动换行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12080942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 01:18:15  来源:igfitidea点击:

Word wrap for NSMutableAttributedString

objective-ciosxcodeios5nsstring

提问by Lollypop

I have NSMutableAttributedString and the string is pretty long. I would like to do word wrap while displaying it on the UIlabel. If it was NSString, i will go ahead and do something like this, Dynamic UILabel truncating the textBut how can i do it with NSAttributedString ? And once it is done, i need to resize the view depending on the label size.

我有 NSMutableAttributedString 并且字符串很长。我想在 UIlabel 上显示时自动换行。如果它是 NSString,我会继续做这样的事情, 动态 UILabel 截断文本但是我怎么能用 NSAttributedString 做到这一点?一旦完成,我需要根据标签大小调整视图大小。

回答by python

The lineBreakMode property isn't deprecated in iOS 6. It has simply changed the names of the constants. The old constants are deprecated, but still available. You can use the new constants even if you are deploying to an older iOS, because the constants are just enum values. The old names and the new names have the same values. So, just set yourlabelname.lineBreakMode = NSLineBreakByTruncatingTail.

lineBreakMode 属性在 iOS 6 中没有被弃用。它只是更改了常量的名称。旧常量已弃用,但仍然可用。即使您部署到较旧的 iOS,您也可以使用新常量,因为这些常量只是枚举值。旧名称和新名称具有相同的值。所以,只需设置 yourlabelname.lineBreakMode = NSLineBreakByTruncatingTail。

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineBreakMode:NSLineBreakByTruncatingTail];
[attributedStr addAttribute:NSParagraphStyleAttributeName
                     value:paragraphStyle
                     range:NSMakeRange(0,[attributedStr length])];

回答by Nishitha

Following also works irrespective of using attributedTextor normal text. Make sure to add the below line after setting the AttributedTextand font to the label.

无论使用attributedText文本还是普通文本,以下内容也都有效。确保在将AttributedText和 字体设置到标签后添加以下行。

label.lineBreakMode = .byTruncatingTail