iOS中自动断字(hyphenationFactor)的使用
项目中某个cell需要显示一个长文本,要求是中英文都要显示。英文如果在行尾需要用-拆分为两个。我们知道如果要把英文拆分,应该用NSLineBreakByCharWrapping,
于是我们写了如下代码:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:content];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
//两边对齐
paragraphStyle.alignment = NSTextAlignmentJustified;
paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
CGFloat offset = 2;
[paragraphStyle setLineSpacing:offset];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, content.length)];
self.carName.attributedText = attributedString;
但是如果文本过长,就会发现有的显示不出来,如图:
9CC52B74-D52C-4F3A-B652-89888C479947.png
(照顾隐私,加了马赛克)
于是我们想起来,应该用NSLineBreakByTruncatingTail在文本末尾显示省略号,然而,然而,NSLineBreakByTruncatingTail 和NSLineBreakByCharWrapping,这两个是同一个属性的, 我们查看下NSParagraphStyle的lineBreakMode这个属性,发现并不是位操作符。这可咋整啊。。
经过反复查找,功夫不负有心人。找到了一篇文章。
UILabel中英文显示折行
发现了paragraphStyle的hyphenationFactor这个属性。
在 Apple 开发者参考文档中,我们能找到 TextKit 有关自动断字
hyphenationFactor属性的描述:
查看下文档中
Hyphenation is attempted when the ratio of the text width (as broken without hyphenation) to the width of the line fragment is less than the hyphenation factor. When the paragraph’s hyphenation factor is 0.0, the layout manager’s hyphenation factor is used instead. When both are 0.0, hyphenation is disabled. This property detects the user-selected language by examining the first item in preferredLanguages.
Soga,这个是连字符属性,取值 0 到 1 之间,可以断词。(具体设置为0.几,文章中说了,我也没太看明白。于是我就设置了0.7)
在上面的代码中加上这句话:
paragraphStyle.hyphenationFactor = 0.7;
重新跑一遍。。。。。。
为啥不好使!
继续按关键词hyphenationFactor找吧。找到了这篇文章
按照文章中,给NSLocale加了个Category,将preferredLanguages转换为英文。
#import "NSLocale+ForceHyphenation.h"
@implementation NSLocale (ForceHyphenation)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
SEL originalSelector = @selector(preferredLanguages);
SEL swizzledSelector = @selector(sr_preferredLanguages);
Class class = object_getClass((id)self);
Method originalMethod = class_getClassMethod(class, originalSelector);
Method swizzledMethod = class_getClassMethod(class, swizzledSelector);
BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
+ (NSArray <NSString *> *)sr_preferredLanguages {
[self sr_preferredLanguages];
return @[ @"en" ];
}
@end
build..
run..
...
3CF3DF8C-82AA-4B12-AFE2-C47D277F1CFC.png
好激动,终于成功了。。
😄😄😄😄😄😄😄
写这篇文章,希望有相同遭遇的同学能看到吧。
另外,利用YYText设置truncationToken可以完美的实现这项功能,而且效率比这个高,感兴趣的同学可以看下下面的demo:
https://github.com/zgsddzwj/WJLabelDemo
本人QQ:297959735 邮箱:zgsddzwj@163.com,欢迎提意见。