在UILabel中的单词分隔符上添加连字符

时间:2013-09-24 10:49:15

标签: ios uilabel word-wrap hyphen nsparagraphstyle

如何设置UILabel lineBreakMode来破坏单词并为断言添加连字符?

  

一个破碎的标签 -

     

rd应该是这样的

5 个答案:

答案 0 :(得分:34)

在这里阐述Matt的答案:https://stackoverflow.com/a/16502598/196358可以使用NSAttributedString和NSParagraphStyle完成。见下文:

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.hyphenationFactor = 1.0f;

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:titleString attributes:@{ NSParagraphStyleAttributeName : paragraphStyle }];

self.titleLabel.attributedText = attributedString;

这将导致标签在使用连字符的中间词的逻辑位置处中断。它看起来很棒,而且非常简单。它需要iOS 6.0,但我只在7.0下尝试过。

答案 1 :(得分:12)

Swift 4.0

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.hyphenationFactor = 1.0

let hyphenAttribute = [
    NSAttributedStringKey.paragraphStyle : paragraphStyle,
    ] as [NSAttributedStringKey : Any]

let attributedString = NSMutableAttributedString(string: "Your String", attributes: hyphenAttribute)
self.yourLabel.attributedText = attributedString

Swift 3.0

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.hyphenationFactor = 1.0
let attributedString = NSMutableAttributedString(string: “Your String”, attributes: [NSParagraphStyleAttributeName:paragraphStyle])
self.yourLabel.attributedText = attributedString

来自故事板

enter image description here

答案 2 :(得分:3)

有时添加locale属性键至关重要。

NSString *lorem = @"Lorem ipsum <et cetera>.";

NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.hyphenationFactor = 1;
paragraph.alignment = NSTextAlignmentJustified;
paragraph.lineBreakMode = NSLineBreakByWordWrapping;

self.label.attributedText = [[NSAttributedString alloc] initWithString:lorem attributes:@{
    NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleBody],
    NSForegroundColorAttributeName: [UIColor darkGrayColor],
    NSParagraphStyleAttributeName: paragraph,
    @"locale": @"la", // Latin, use @"en-US" for American English, for example.
}];

答案 3 :(得分:1)

我不能删除它,因为它已被接受,但从今天的POV我错了。

EARLIER UILabel没有提供连字符 它通过NSAttributedString(ios6 +)

来完成

请参阅:Orthographic hyphenation word in IOS 6.x

答案 4 :(得分:0)

这会对你有所帮助。请将Uilabel Text plain更改为Attributed enter image description here