我剛剛將這個作爲NSString
的一個類別用於最近的項目,似乎工作正常。它目前與寬度一起工作,但您應該能夠適應它以使用高度。
的NSString-Truncate.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface NSString (Truncate)
- (NSString *)stringByTruncatingToWidth:(CGFloat)width attributes:(NSDictionary *)textFontAttributes;
@end
的NSString-Truncate.m
#import "NSString+Truncate.h"
@implementation NSString (Truncate)
- (NSString *)stringByTruncatingToWidth:(CGFloat)width attributes:(NSDictionary *)textFontAttributes {
CGSize size = [self sizeWithAttributes:textFontAttributes];
if (size.width <= width) {
return self;
}
for (int i = 2; i < self.length; i++) {
NSString *testString = [NSString stringWithFormat:@"%@…", [self substringToIndex:self.length - i]];
CGSize size = [testString sizeWithAttributes:textFontAttributes];
if (size.width <= width) {
return testString;
}
}
return @"";
}
@end
的可能重複的[iOS的7 sizeWithAttributes:替代sizeWithFont:constrainedToSize](HTTP:// stackoverflow.com/questions/19145078/ios-7-sizewithattributes-replacement-for-sizewithfontconstrainedtosize) –
可能的重複不會返回截斷的字符串,只是大小。 – picciano