截取固定宽度字符串

时间:2025-03-29 21:11:24
#import <CoreText/>
/// 截取固定宽度字符串
- (NSString *)getVisibleStringWithWidth:(CGFloat)width font:(UIFont *)font str:(NSString*)str {
    NSMutableParagraphStyle *p = [[NSMutableParagraphStyle alloc] init];
     = 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, ), , NULL);
    CFRange range = CTFrameGetVisibleStringRange(frame);
    CFRelease(framesetter);
    CFRelease(frame);
    return [str substringWithRange:NSMakeRange(, )];
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

使用

 CGSize size = [ danamicGetWidthFromTextWithFont:[Apperance ChineseFontMediumSize:14]];
    float total =  + 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:];
         = [NSString stringWithFormat:@"%@...",newStr];
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7