add hyphens on word break in a UILabel

2019-01-17 04:33发布

How do I set a UILabel lineBreakMode to break words and add hyphens to broken words?

a label with a broken wo-

rd should look like this

5条回答
甜甜的少女心
2楼-- · 2019-01-17 04:47

This will help you. please Change Uilabel Text plain to Attributed enter image description here

查看更多
Juvenile、少年°
3楼-- · 2019-01-17 04:56

Elaborating on Matt's answer here: https://stackoverflow.com/a/16502598/196358 it can be done using NSAttributedString and NSParagraphStyle. See below:

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

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

self.titleLabel.attributedText = attributedString;

This will cause the label to break at logical places mid-word using hyphens. It looks great, and is pretty simple to do. It requires iOS 6.0, but I've only tried it under 7.0.

查看更多
狗以群分
4楼-- · 2019-01-17 05:02

Sometimes it's crucial to add a locale attribute key.

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.
}];
查看更多
做个烂人
5楼-- · 2019-01-17 05:05

I can't delete this as it was accepted, but I am wrong from today's POV.

EARLIER UILabel did not offer Hyphenation.
TODAY it does through NSAttributedString (ios6+)

see: Orthographic hyphenation word in IOS 6.x

查看更多
Deceive 欺骗
6楼-- · 2019-01-17 05:07

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

From Storyboard

enter image description here

查看更多
登录 后发表回答