10

問題

長さの途中でピシャリと鳴る可能性のある Unicode 文字を全滅させずに、特定の長さで文字列を切り捨てるにはどうすればよいですか? 見苦しい文字列を作成しないように、文字列内の Unicode 文字の先頭のインデックスを特定するにはどうすればよいですか。A の半分が表示されている四角形は、切り捨てられた別の絵文字の位置です。

-(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答えのおかげで、私のニーズに合わせて1つの簡単な機能を使用することができました!

-(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;

}
4

2 に答える 2