CoreText or TextKit
You need to add a soft wrap to the string. These are “-” that are not visible during visualization, but instead are just queues for CoreText or UITextKit to know how to break words.
The soft hyphen icon you should put in the text:
unichar const kTextDrawingSoftHyphenUniChar = 0x00AD; NSString * const kTextDrawingSoftHyphenToken = @"";
Code example
NSString *string = @"accessibility tests and frameworks checking"; NSLocale *locale = [NSLocale localeWithLocaleIdentifier:@"en_US"]; NSString *hyphenatedString = [string softHyphenatedStringWithLocale:locale error:nil]; NSLog(@"%@", hyphenatedString);
Outputs ac-ces-si-bil-i-ty tests and frame-works check-ing
NSString + SoftHyphenation.h
typedef enum { NSStringSoftHyphenationErrorNotAvailableForLocale } NSStringSoftHyphenationError; extern NSString * const NSStringSoftHyphenationErrorDomain; @interface NSString (SoftHyphenation) - (NSString *)softHyphenatedStringWithLocale:(NSLocale *)locale error:(out NSError **)error; @end
NSString + SoftHyphenation.m
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(int i = string.length - 1; i > 0; i--) { if(hyphenationLocations[i]) { [string insertString:@"-" atIndex:i]; } } if(error != NULL) { *error = nil;} return string; } } @end
hfossli
source share