我创建了一个UILabel。当文本太长时,我希望使用(.. more)替换(...)。我已经尝试过了,但我没有要求结果。
UILabel * writtenContentLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, ScreenWidth - 20 , 70)];
writtenContentLabel.numberOfLines = 0;
writtenContentLabel.text = [str stringByAppendingString:@"More"];
writtenContentLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
[self addSubview:writtenContentLabel];
我该怎么办?
答案 0 :(得分:3)
您必须使用自定义标签视图才能实现此目的。
将UILabels
替换为以下任何自定义标签。它们都支持自定义truncationTokenString
方法。
MDHTMLLabel
https://github.com/mattdonnelly/MDHTMLLabel (我推荐此控件) TTTAtributtedLabel
https://github.com/mattt/TTTAttributedLabel 您可以使用
更改默认省略号 [label setTruncationTokenString:@"...More"];
答案 1 :(得分:0)
您可以使用以下方法:
- (NSString*)stringWithElipsisMore:(NSString*)oringinalStr withLabel:(UILabel*)label
{
CGRect rect = label.frame;
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
NSDictionary * attributes = @{NSFontAttributeName:label.font, NSParagraphStyleAttributeName:paragraphStyle};
const CGSize maxSize = CGSizeMake(rect.size.width, CGFLOAT_MAX);
CGSize stringSize = [oringinalStr boundingRectWithSize:maxSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil].size;
if (stringSize.height > rect.size.height) {
float proportion = rect.size.height / stringSize.height;
NSString *subStr = [oringinalStr substringToIndex:oringinalStr.length * proportion];
CGSize stringSize = [subStr boundingRectWithSize:maxSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil].size;
while (stringSize.height < rect.size.height) {
subStr = [oringinalStr substringToIndex:subStr.length + 1];
stringSize = [subStr boundingRectWithSize:maxSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil].size;
}
subStr = [subStr substringToIndex:subStr.length - 1];
while (stringSize.height > rect.size.height){
subStr = [subStr substringToIndex:subStr.length - 1];
stringSize = [subStr boundingRectWithSize:maxSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil].size;
}
NSRange range = NSMakeRange(subStr.length - 7, 7);
NSString *subSubStr = [subStr stringByReplacingCharactersInRange:range withString:@"...more"];
return subSubStr;
} else {
return oringinalStr;
}
}
NSString *subStr = [self stringWithElipsisMore:str withLabel:writtenContentLabel];
writtenContentLabel.text = subStr;