截断一个字符串

Tro*_*sen 1 cocoa objective-c nstableview

我有一个NSTableView,它在一列中显示文件的路径.当用户调整tableview的大小时,我希望调整路径名(例如/Users/name/testfile.m)的大小,但我希望路径名的末尾(例如... name/testfile.m)可见,而不是默认情况下启动(例如/ Users/test/te ...)路径.我写了一个成功完成我想做的功能,但是当用户缩放tableview时,tableview会在重绘时闪烁.我认为必须有一个更好,更优雅的算法,但我已经查看了NSString和Stackoverflow的文档,我找不到任何可以提供更好解决方案的东西.如果有人对这个问题有一个更优雅的解决方案,将不胜感激.谢谢!干杯,特隆德

我目前的职能:

-(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;
}
Run Code Online (Sandbox Code Playgroud)

jus*_*tin 5

典型的方法很简单:

[tableViewCell setLineBreakMode:NSLineBreakByTruncatingHead];
Run Code Online (Sandbox Code Playgroud)

正如Dondragmer所说,这个属性也可以在Xcode的NIB编辑器中设置.

  • 您也可以通过选择单元格(而不仅仅是列)并在那里更改换行模式在Interface Builder中执行此操作.同样的效果,只适用于不同的地方. (2认同)