假设我有The Dark Knight Rises at 7:45pm,我需要将它放入一个固定宽度的UILabel (对于iPhone)。我该如何将其缩短为“黑暗骑士崛起...在晚上7:45”而不是“黑暗骑士在7:4崛起...”?
发布于 2012-12-17 07:20:21
UILabel具有以下属性:
@property(nonatomic) NSLineBreakMode lineBreakMode;您可以通过将其设置为NSLineBreakByTruncatingMiddle来启用该行为。
编辑
我不理解你为什么只想截短string.Then的一部分,请阅读下面的内容:
如果只想将换行模式应用于文本的一部分,请使用所需的样式信息创建一个新的属性字符串,并将其与标签关联。如果未使用带样式的文本,则此属性将应用于text属性中的整个文本字符串。
示例
因此,甚至有一个用于设置段落样式的类: NSParagraphStyle,它还有一个可变版本。
因此,假设您有一个要应用该属性的范围:
NSRange range=NSMakeRange(i,j);你必须创建一个NSMutableParagraphStyle对象,并将它的lineBreakMode设置为NSLineBreakByTruncatingMiddle.Notice,这样你也可以设置很多其他的parameters.So,让我们这样做:
NSMutableParagraphStyle* style= [NSMutableParagraphStyle new];
style.lineBreakMode= NSLineBreakByTruncatingMiddle;然后在range.The attributedText属性中为标签的attributedText添加该属性,该属性是一个NSAttributedString,而不是NSMutableAttributedString,因此您必须创建一个NSMutableAttributedString并将其分配给该属性:
NSMutableAttributedString* str=[[NSMutableAttributedString alloc]initWithString: self.label.text];
[str addAttribute: NSParagraphStyleAttributeName value: style range: range];
self.label.attributedText= str;注意,NSAttributedString还有很多其他属性,请检查here。
发布于 2012-12-17 07:19:25
您必须设置lineBreakMode。您可以通过接口生成器或以编程方式执行此操作,如下所示
label.lineBreakMode = NSLineBreakByTruncatingMiddle;请注意,从iOS 5开始,此类属性的类型从UILineBreakMode更改为NSLineBreakMode。
发布于 2012-12-17 09:07:33
我的第一个想法是两个标签并排放在一起,都有固定的宽度,但我假设你已经出于某种未明的原因排除了这一点。或者,手动计算截断,如下所示...
- (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];
}这样叫它:
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;这会生成:@"The Dark Kni...at 7:45 The“
https://stackoverflow.com/questions/13906431
复制相似问题