Skip to content

Latest commit

 

History

History
150 lines (127 loc) · 6.32 KB

字符串处理相关.md

File metadata and controls

150 lines (127 loc) · 6.32 KB

UITextFiled或UITextView字数限制最好的方法

Objc中国

  • 幸运的是,NSString 有更好地方式:enumerateSubstringsInRange:options:usingBlock: 方法。这个方法把 Unicode 抽象的地方隐藏了,能让你轻松地循环字符串里的组合字符串、单词、行、句子或段落。 你甚至可以加上 NSStringEnumerationLocalized 这个选项,这样可以在确定词语间和句子间的边界时把用户所在的区域考虑进去。 要遍历单个字符,把参数指定为 NSStringEnumerationByComposedCharacterSequences:
  • 这个奇妙的方法表明,苹果想让我们把字符串看做子字符串的集合,而不是(苹果意义上的)字符的集合,因为
    • 单个 unichar 太小,不足以代表一个真正的 Unicode 字符;
    • 一些(普遍意义上的)字符由多个 Unicode 码点组成。
    • 请注意,这个方法的加入相对晚一些(在 OS X 10.6 和 iOS 4.0 的时候)。在之前,按字符循环一个字符串要麻烦得多。
NSString *s = @"The weather on \U0001F30D is \U0001F31E today.";  
// The weather on 🌍 is 🌞 today.  
NSRange fullRange = NSMakeRange(0, [s length]);  
[s enumerateSubstringsInRange:fullRange  
                      options:NSStringEnumerationByComposedCharacterSequences  
                   usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop)
{
    NSLog(@"%@ %@", substring, NSStringFromRange(substringRange));
}];

富文本字符连接处理(自动断字)

  • TextKit的富文本属性
\*
 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
*\
iOS 中非常简单,TextKit 提供了良好的自动断字支持,可以通过设置 hyphenationFactor 属性非常方便的实现自动断字:
let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.hyphenationFactor = 1
    paragraphStyle.alignment = .center
    
#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
  • 利用YYText设置truncationToken可以完美的实现这项功能,而且效率比这个高
  • 扩展处理的简单方法
#import "NSString+SoftHyphenation.h"
unichar const kTextDrawingSoftHyphenUniChar = 0x00AD;
NSString * const kTextDrawingSoftHyphenToken = @"\u00ad"; // NOTE: UTF-8 soft hyphen!

NSString * const NSStringSoftHyphenationErrorDomain = @"NSStringSoftHyphenationErrorDomain";

@implementation NSString (SoftHyphenation)

- (NSError *)hyphen_createOnlyError
{
    NSDictionary *userInfo = @{
                               NSLocalizedDescriptionKey: @"Hyphenation is not available for given locale",
                               NSLocalizedFailureReasonErrorKey: @"Hyphenation is not available for given locale",
                               NSLocalizedRecoverySuggestionErrorKey: @"You could try using a different locale even though it might not be 100% correct"
                               };
    return [NSError errorWithDomain:NSStringSoftHyphenationErrorDomain code:NSStringSoftHyphenationErrorNotAvailableForLocale userInfo:userInfo];
}

- (NSString *)softHyphenatedStringWithLocale:(NSLocale *)locale error:(out NSError **)error
{
    CFLocaleRef localeRef = (__bridge CFLocaleRef)(locale);
    if(!CFStringIsHyphenationAvailableForLocale(localeRef))
    {
        if(error != NULL)
        {
            *error = [self hyphen_createOnlyError];
        }
        return [self copy];
    }
    else
    {
        NSMutableString *string = [self mutableCopy];
        unsigned char hyphenationLocations[string.length];
        memset(hyphenationLocations, 0, string.length);
        CFRange range = CFRangeMake(0, string.length);
        
        for(int i = 0; i < string.length; i++)
        {
            CFIndex location = CFStringGetHyphenationLocationBeforeIndex((CFStringRef)string,
                                                                         i,
                                                                         range,
                                                                         0,
                                                                         localeRef,
                                                                         NULL);
            
            if(location >= 0 && location < string.length)
            {
                hyphenationLocations[location] = 1;
            }
        }
        
        for(unsigned long i = string.length - 1; i > 0; i--)
        {
            if(hyphenationLocations[i])
            {
                [string insertString:kTextDrawingSoftHyphenToken atIndex:i];
            }
        }
        
        if(error != NULL) { *error = nil;}
        
        return string;
    }
}


- (NSString *)softHyphenatedString
{
    NSLocale *locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
    return [self softHyphenatedStringWithLocale:locale error:nil];
}


@end