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

Dav*_*Ari 17 hyphen word-wrap uilabel ios nsparagraphstyle

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

一个破碎的标签 -

rd应该是这样的

Ken*_*ker 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;
Run Code Online (Sandbox Code Playgroud)

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

  • 我还需要一点点.从Apple doc,"hyphenationFactor有效值介于0.0和1.0之间".我降低了值以增加对连字符的抵抗力. (2认同)

Kru*_*nal 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
Run Code Online (Sandbox Code Playgroud)

Swift 3.0

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

来自故事板

在此输入图像描述


bte*_*pot 5

有时添加属性键至关重要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.
}];
Run Code Online (Sandbox Code Playgroud)