如果UILabel的内容不适合,请更改文本末尾的默认“...”

时间:2012-05-01 00:36:40

标签: iphone objective-c uilabel

我的iPhone项目中有一个UILabel,它具有固定的宽度和高度,但它的内容可能因用户所看到的而异。有时文本对UILabel来说很大,那就是当字符串:'...'被添加到行尾时。我想知道我是否可以将此字符串更改为其他内容,例如:'(more)'。

谢谢!

3 个答案:

答案 0 :(得分:2)

不幸的是,根据这个类似的问题,iOS上似乎没有包含此类选项:How to change truncate characters in UILabel?

然而,正如上述问题中的答案所述,这可以自己轻松完成。您真正需要做的就是找到字符串被截断的位置并减去所选结束字符所需的数量。然后将余数放在一个单独的字符串中。

对于这种方法,这个答案也很有用:

  

正如Javanator所说,你必须自己截断。你shuld使用sizeWithFont:forWidth:lineBreakMode:消息对UIKit添加到NSString类以获取具有特定字体的字符串的宽度。这将处理所有类型的字体。

答案 1 :(得分:1)

我认为这是一个有趣的问题,因此构建并且几乎没有测试过这个......

- (void)setText:(UILabel *)label withText:(NSString *)text andTruncationSuffix:(NSString *)truncationSuffix {

    // just set the text if it fits using the minimum font
    //
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:label.minimumFontSize]];
    if (size.width <= label.bounds.size.width) {
        label.text = text;
        return;
    }

    // build a truncated version of the text (using the custom truncation text)
    // and shrink the truncated text until it fits
    NSInteger lastIndex = text.length;
    CGFloat width = MAXFLOAT;

    NSString *subtext, *ellipticalText;

    while (lastIndex > 0 && width > label.bounds.size.width)  {
        subtext = [text substringToIndex:lastIndex];
        ellipticalText = [subtext stringByAppendingString:truncationSuffix];
        width = [ellipticalText sizeWithFont:[UIFont systemFontOfSize:label.minimumFontSize]].width;
        lastIndex--;
    }
    label.text = ellipticalText;
}

这样称呼:

[self setText:self.label withText:@"Now is the time for all good men to come to the aid of their country" andTruncationSuffix:@" more"];

如果这对您有用,您可以考虑添加UILabel的子类,使用它来覆盖setText:方法,并添加名为truncatedSuffix的属性。

答案 2 :(得分:1)

如果您使用的是iOS版本&gt; 8.0,您可以使用ResponsiveLabel。在这里,您可以提供自定义截断标记以及定义操作以使其可以自定义。

NSString *expansionToken = @"Read More ...";
NSString *str = @"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:kExpansionToken attributes:@{NSForegroundColorAttributeName:[UIColor blueColor],NSFontAttributeName:self.customLabel.font}];
[self.customLabel setAttributedTruncationToken:attribString withAction:^(NSString *tappedString) {
 NSLog(@"Tap on truncation text");
}];
[self.customLabel setText:str withTruncation:YES];