Trond Kristiansen
Trond Kristiansen

Reputation: 2446

Truncate a string

I have a NSTableView that shows the path of files in one column. When the user resizes the tableview I want the pathname (e.g. /Users/name/testfile.m) to be resized, but I want the end of the pathname (e.g. ...name/testfile.m) to be visible and not the start (e.g. /Users/test/te...) of the path as happens by default. I wrote a function that successfully does what I want to do, but the tableview flickers while redrawing as the user scales the tableview. I think there must be a better, more elegant algorithm for doing this, but I have looked into the documentation for NSString and on Stackoverflow and I cant find anything that gives a better solution. If anyone has a more elegant solution to this problem that would be greatly appreciated. Thanks! Cheers, Trond

My current function:

-(NSString *) truncateString:(NSString *) myString withFontSize:(int) myFontSize withMaxWidth:(NSInteger) maxWidth
{
    // Get the width of the current string for a given font
    NSFont *font = [NSFont systemFontOfSize:myFontSize];
    CGSize textSize = NSSizeToCGSize([myString sizeWithAttributes:[NSDictionary     dictionaryWithObject:font forKey: NSFontAttributeName]]);
    NSInteger lenURL =(int)textSize.width;

    // Prepare for new truncated string
    NSString *myStringShort;
    NSMutableString *truncatedString = [[myString mutableCopy] autorelease];

    // If the available width is smaller than the string, start truncating from first character
    if (lenURL > maxWidth)
    {
        // Get range for first character in string
        NSRange range = {0, 1};

        while ([truncatedString sizeWithAttributes:[NSDictionary dictionaryWithObject:font forKey: NSFontAttributeName]].width  > MAX(TKstringPad,maxWidth)) 
        {
            // Delete character at start of string
            [truncatedString deleteCharactersInRange:range];
        }     
        myStringShort = [NSString stringWithFormat:@"...%@",truncatedString];
    }
    else
    {
        myStringShort=myString;
    }
    return myStringShort;
}

Upvotes: 1

Views: 590

Answers (1)

justin
justin

Reputation: 104698

The typical approach would be simply:

[tableViewCell setLineBreakMode:NSLineBreakByTruncatingHead];

As Dondragmer noted, this property may also be set in Xcode's NIB editor.

Upvotes: 5

Related Questions