6

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

谢谢!

4

3 回答 3

2

不幸的是,根据这个类似的问题,iOS 中似乎不包含这样的选项:如何更改 UILabel 中的截断字符?

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

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

正如Javanator所说,您必须自己进行截断。您应该在 UIKit 添加到 NSString 类时使用 sizeWithFont:forWidth:lineBreakMode: 消息来获取具有特定字体的字符串的宽度。这将处理所有类型的字体。

于 2012-05-01T02:36:38.720 回答
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 的属性。

于 2012-05-01T02:44:25.343 回答
1

如果您使用的是 iOS 版本 > 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];
于 2015-08-05T07:53:59.410 回答