#import <CoreText/CoreText.h>
/// 截取固定宽度字符串
- (NSString *)getVisibleStringWithWidth:(CGFloat)width font:(UIFont *)font str:(NSString*)str {
NSMutableParagraphStyle *p = [[NSMutableParagraphStyle alloc] init];
p.lineBreakMode = NSLineBreakByCharWrapping;
NSAttributedString *namesAtt = [[NSAttributedString alloc] initWithString:str attributes:@{NSFontAttributeName:font, NSParagraphStyleAttributeName:p}];
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)namesAtt);
UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, width, 25.)];
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, str.length), path.CGPath, NULL);
CFRange range = CTFrameGetVisibleStringRange(frame);
CFRelease(framesetter);
CFRelease(frame);
return [str substringWithRange:NSMakeRange(range.location, range.length)];
}
使用
CGSize size = [model.storeName danamicGetWidthFromTextWithFont:[Apperance ChineseFontMediumSize:14]];
float total = size.width + DeviceX(12) + DeviceX(60);
if(total>DeviceX(283)){
float maxWidth = DeviceX(283) - DeviceX(12) - DeviceX(60) - DeviceX(15);
NSString *newStr = [self getVisibleStringWithWidth:maxWidth font:[LCApperance LCChineseFontMediumSize:14] str:model.storeName];
model.storeName = [NSString stringWithFormat:@"%@...",newStr];
}