
How can I truncate a string with a given length without invalidating the unicode character, which could be a hit in the middle of my length? How to determine the index of the beginning of a Unicode character in a string so that I can avoid creating ugly strings. A square with half visible A is the location of another emoji symbol that has been truncated.
-(NSMutableAttributedString*)constructStatusAttributedStringWithRange:(CFRange)range NSString *original = [_postDictionay objectForKey:@"message"]; NSMutableString *truncated = [NSMutableString string]; NSArray *components = [original componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; for(int x=0; x<[components count]; x++) { //If the truncated string is still shorter then the range desired. (leave space for ...) if([truncated length]+[[components objectAtIndex:x] length]<range.length-3) { //Just checking if its the first word if([truncated length]==0 && x==0) { //start off the string [truncated appendString:[components objectAtIndex:0]]; } else { //append a new word to the string [truncated appendFormat:@" %@",[components objectAtIndex:x]]; } } else { x=[components count]; } } if([truncated length]==0 || [truncated length]< range.length-20) { truncated = [NSMutableString stringWithString:[original substringWithRange:NSMakeRange(range.location, range.length-3)]]; } [truncated appendString:@"..."]; NSMutableAttributedString *statusString = [[NSMutableAttributedString alloc]initWithString:truncated]; [statusString addAttribute:(id)kCTFontAttributeName value:[StyleSingleton streamStatusFont] range:NSMakeRange(0, [statusString length])]; [statusString addAttribute:(id)kCTForegroundColorAttributeName value:(id)[StyleSingleton streamStatusColor].CGColor range:NSMakeRange(0, [statusString length])]; return statusString; }
UPDATE . Thanks to the answer, I was able to use one simple function for my needs!
-(NSMutableAttributedString*)constructStatusAttributedStringWithRange:(CFRange)range { NSString *original = [_postDictionay objectForKey:@"message"]; NSMutableString *truncated = [NSMutableString stringWithString:[original substringWithRange:[original rangeOfComposedCharacterSequencesForRange:NSMakeRange(range.location, range.length-3)]]]; [truncated appendString:@"..."]; NSMutableAttributedString *statusString = [[NSMutableAttributedString alloc]initWithString:truncated]; [statusString addAttribute:(id)kCTFontAttributeName value:[StyleSingleton streamStatusFont] range:NSMakeRange(0, [statusString length])]; [statusString addAttribute:(id)kCTForegroundColorAttributeName value:(id)[StyleSingleton streamStatusColor].CGColor range:NSMakeRange(0, [statusString length])]; return statusString; }
ios objective-c unicode nsstring emoji
Piotr Tomasik Apr 02 '13 at 10:06
source share