我需要在两行中显示一些文字,例如
|一个非常大的字符串字符串|
| string string ... - 后缀字符串|
整篇文章包含两部分
如何在iOS中实现它?
答案 0 :(得分:0)
您必须设置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)