iOS:截断一个大字符串,并附加一个后缀字符串

时间:2015-08-18 07:45:26

标签: ios uitextfield uilabel

我需要在两行中显示一些文字,例如

|一个非常大的字符串字符串|

| string string ... - 后缀字符串|

整篇文章包含两部分

  1. 一个大型描述字符串,需要截断
  2. " -a后缀字符串",不会被截断
  3. 如何在iOS中实现它?

2 个答案:

答案 0 :(得分:0)

如果将其设置为NSLineBreakByTruncatingMiddleit将在中间截断。

您必须设置lineBreakMode。您可以从Interface Builder或以编程方式执行此操作,如下所示

  label.lineBreakMode = NSLineBreakByTruncatingMiddle;

另一种解决方案

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160, 21)];
NSString *string = @"The Dark Knight Rises at 7:45pm";
NSString *substring = @"at";
CGFloat pix = 120.0;
NSString *result = [self truncatedStringFrom:string toFit:label atPixel:120.0 atPhrase:@"at"];

label.text = result;
  

我的第一个想法是两个标签并排,两个都有固定的宽度,   但是我会假设你已经因为一些未说明的原因而排除了这一点。   或者,手动计算截断,如下所示......

- (NSString *)truncatedStringFrom:(NSString *)string toFit:(UILabel *)label
                          atPixel:(CGFloat)pixel atPhrase:(NSString *)substring {

    // truncate the part of string before substring until it fits pixel
    // width in label

    NSArray *components = [string componentsSeparatedByString:substring];
    NSString *firstComponent = [components objectAtIndex:0];
    CGSize size = [firstComponent sizeWithFont:label.font];

    NSString *truncatedFirstComponent = firstComponent;

    while (size.width > pixel) {
        firstComponent = [firstComponent substringToIndex:[firstComponent length] - 1];
        truncatedFirstComponent = [firstComponent stringByAppendingString:@"..."];
        size = [truncatedFirstComponent sizeWithFont:label.font];
    }

    NSArray *newComponents = [NSArray arrayWithObjects:truncatedFirstComponent, [components lastObject], nil];
    return [newComponents componentsJoinedByString:substring];
}

答案 1 :(得分:0)

请执行此操作并告诉我..