如何知道适合固定大小的UILabel的NSString的长度?

时间:2011-06-21 08:57:17

标签: iphone nsstring size uilabel

我知道NSString有一些方法可以确定它的帧大小,使用NSString UIKit Additions,sizeWithFont ......

反过来怎么样?我的意思是如果我有一个固定的帧大小,我如何知道NSString中可以容纳多少个字符或单词呢?

如果我知道这一点,我可以轻松切断NSString。

感谢

4 个答案:

答案 0 :(得分:7)

它可能不是最优雅的解决方案,但你可以这样做:

- (NSString *)string:(NSString *)sourceString reducedToWidth:(CGFloat)width withFont:(UIFont *)font {

    if ([sourceString sizeWithFont:font].width <= width)
        return sourceString;

    NSMutableString *string = [NSMutableString string];

    for (NSInteger i = 0; i < [sourceString length]; i++) {

        [string appendString:[sourceString substringWithRange:NSMakeRange(i, 1)]];

        if ([string sizeWithFont:font].width > width) {

            if ([string length] == 1)
                return nil;

            [string deleteCharactersInRange:NSMakeRange(i, 1)];

            break;
        }
    }

    return string;
}

然后这样称呼:

NSString *test = @"Hello, World!";
CGFloat width = 40.0;
UIFont *font = [UIFont systemFontOfSize:[UIFont labelFontSize]];

NSString *reducedString = [self string:test reducedToWidth:width withFont:font];

NSLog(@"%@", reducedString);

答案 1 :(得分:1)

您无法知道/确定适合具有固定宽度的UILabel的字符数,因为某些字符比其他字符更稀疏,例如l和m。

有两种选择:

  1. 使用Mono-Space-Fonts(每个字符也有固定的宽度)。然后使用字体大小确定字体中一个字符的宽度并计算字符数
  2. 允许任意数量的字符,如果插入的字符适合,请检查插入。
  3. 你必须知道你想要的行为。如果文本不适合会发生什么。如果您只想截断(就像mortenfast的解决方案那样),那么只需使用UILineBreakModeTailTruncation作为lineBreakMode的{​​{1}}属性(还有更多选项,如TruncateHead,Clip,Word裹)

答案 2 :(得分:0)

谢谢@Morten。我已更新示例代码以处理单词分隔。它还消除了单词之间的额外空格。它尚未在现场进行测试,但到目前为止,我的测试证明是可以的。如果您发现改进或错误/故障修复,请随意更新。

-(NSString*)string:(NSString*)sourceString reducedToWidth:(CGFloat)width withFont:(UIFont*)font {

    // if full string is within bounds, simply return the full string
    if( [sourceString sizeWithFont:font].width <= width ) return sourceString;

    // break up string into words. if <= 1 word, return original string
    NSArray* words = [sourceString componentsSeparatedByString:@" "];
    NSInteger numWords = [words count];
    if( numWords <= 1 ) return sourceString;

    // our return var. we populate as we go
    NSMutableString* str = [NSMutableString string];
    // temp var to test with before adding to return string
    NSMutableString* strTemp = [NSMutableString string];
    // string to hold word LESS spaces
    NSString* strWordTemp = nil;
    // the word we're currently on
    NSInteger numWord = 0;
    // whether we need to add a space (when not last word)
    Boolean addSpace = NO;

    // loop through our words....
    for( NSString* strWord in words ) {

        // which word we're on
        numWord++;

        // eliminate white space
        strWordTemp = [strWord stringByReplacingOccurrencesOfString:@" " withString:@""];

        // if this word is empty or was a space(s), skip it
        if( [strWordTemp isEqualToString:@""] ) continue;

        // append to temp string
        [strTemp appendString:strWordTemp];

        // if we're still within the bounds...
        if( [strTemp sizeWithFont:font].width <= width ) {

            // default = no extra space
            addSpace = NO;

            // if we're not the last word, add a space & check for length
            if( numWord < numWords ) {

                [strTemp appendString:@" "];

                // if adding space made it too long, then just don't add it!
                if( [strTemp sizeWithFont:font].width > width ) {

                    // it was too long with space, so we'll just add word
                    [str appendString:strWordTemp];
                    break;
                }
                // otherwise, it's OK to add the space
                else addSpace = YES;
            }

            // append to return string and continue
            [str appendFormat:@"%@%@", strWordTemp, ( addSpace ? @" " : @"" )];
        }
        // otherwise, we're done
        else break;
    }

    // return our result
    return str;
}

答案 3 :(得分:0)

或者您只需使用lineBreak属性并将其设置为NSLineBreakByCharWrapping并继续您的生活。 https://stackoverflow.com/a/29088337/951349